加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

POJ 3469 最大流 分配问题

(2010-09-26 18:01:12)
标签:

poj

3469

最大流

分配问题

it

分类: 网络流

题目描述:n个任务,两个机器AB,输入n对数字Ai Bi

表示i号任务在A上消耗和在B上的消耗。

然后再给m行,每行a,b,c三个数字。

表示如果a任务和b任务不在一个机器上工作的话,需要额外花费c。

问,所有任务都工作的情况下,最小的花费是多少。

解题报告:

最小割,n个任务用n个点表示。

s和n个点连接,容量是Ai,n个点和t连接,容量是Bi。

对于每个abc,a连接b,容量c,b连接a,容量c。

这样的话,按照最小割的定义,n个任务一些要被分到s,另一些要被分到t,这两部分之间没有边的连接。正好是题目的要求。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define Max 0x1fffffff
#define size 20100
struct edge{int from, to, val, next;}e[2000000];
int v[size], que[size], dis[size], cnt, cur[size];
void insert(int from, int to, int va)
{
    e[cnt].from = from, e[cnt].to = to; e[cnt].val = va;
    e[cnt].next = v[from];v[from] = cnt++;
    e[cnt].from = to, e[cnt].to = from; e[cnt].val = 0;
    e[cnt].next = v[to];v[to] = cnt++;
}
bool bfs(int n, int s, int t)
{
    int head, tail, id;
    head = tail = 0; que[tail++] = s;
    memset(dis, -1, sizeof(int) * n);dis[s] = 0;
    while(head < tail) // bfs,得到顶点i的距s的最短距离dis[i]
        for(id = v[que[head++]]; id != -1; id = e[id].next)
            if (e[id].val > 0 && dis[e[id].to] == -1)
            {
                dis[e[id].to] = dis[e[id].from] + 1;
                que[tail++] = e[id].to;
                if (e[id].to == t) return true;
            }
    return false;
}

int Dinic(int n, int s, int t)
{
    int maxflow = 0, tmp, i;
    while(bfs(n, s, t))
    {
        int u = s, tail = 0;
        for(i = 0; i < n; i++) cur[i] = v[i];
        while(cur[s] != -1)
            if (u != t && cur[u] != -1 && e[cur[u]].val > 0 && dis[u] != -1 && dis[u] + 1 == dis[e[cur[u]].to])
            {que[tail++] = cur[u]; u = e[cur[u]].to;}
            else if (u == t)
            {
                for(tmp = Max, i = tail - 1; i >= 0; i--) tmp = min(tmp, e[que[i]].val);
                for(maxflow += tmp, i = tail - 1; i >= 0; i--)
                {
                    e[que[i]].val -= tmp;
                    e[que[i] ^ 1].val += tmp;
                    if (e[que[i]].val == 0) tail = i;
                }
                u = e[que[tail]].from;
            }
            else
            {
                while(tail > 0 && u != s && cur[u] == -1) u = e[que[--tail]].from;
                cur[u] = e[cur[u]].next;
            }
    }
    return maxflow;
}
int n ,m, a, b, c;
int main()
{
    while(scanf("%d%d", &n, &m) != EOF)
    {
        int s = 0, t = n + 1;
        memset(v, -1, sizeof(int) * (n + 2)); cnt = 0;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d%d", &a, &b);
            insert(s, i, a); insert(i, t, b);
        }
        while(m-- && scanf("%d%d%d", &a, &b, &c)) insert(a, b, c), insert(b, a, c);
        printf("%d\n", Dinic(t + 1, s, t));
    }
    return 0;
}

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有