3396: [Usaco2009 Jan]Total flow 水流
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 615 Solved: 295
[ Submit][ Status][ Discuss]
Description
Input
第1行输入N,之后N行每行描述一条水管,前两个英文字母表示水管的两端(大小写字母是不一样的),后一个整数表示水管的流量,流量不会超过1000.
Output
一个整数,表示总流量.
Sample Input
5
A B 3
B C 3
C D 5
D Z 4
B Z 6
Sample Output
3
这难道就是传说中的最大流??
用Dinic时记得不要用优化
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
int cnt, S, T, head[66], h[66];
typedef struct
{
int to, next;
int flow;
}Road;
Road G[200005];
void Add(int u, int v, int flow)
{
cnt++;
G[cnt].next = head[u];
head[u] = cnt;
G[cnt].to = v;
G[cnt].flow = flow;
}
int Jud()
{
int now, i;
queue<int> q;
memset(h, -1, sizeof(h));
q.push(S);
h[S] = 0;
while(q.empty()==0)
{
now = q.front();
q.pop();
for(i=head[now];i!=0;i=G[i].next)
{
if(G[i].flow && h[G[i].to]==-1)
{
h[G[i].to] = h[now]+1;
q.push(G[i].to);
}
}
}
if(h[T]!=-1)
return 1;
return 0;
}
int Sech(int x, int flow)
{
int w, used, i;
if(x==T)
return flow;
used = 0;
for(i=head[x];i!=0;i=G[i].next)
{
if(h[G[i].to]==h[x]+1)
{
w = Sech(G[i].to, min(flow-used, G[i].flow));
G[i].flow -= w;
G[i^1].flow += w;
used += w;
if(used==flow)
return flow;
}
}
if(used==0)
h[x] = -1;
return used;
}
int Dinic()
{
int i, flow = 0;
while(Jud())
flow += Sech(S, 1<<25);
return flow;
}
int main(void)
{
char a, b;
int m, i, x;
scanf("%d", &m);
cnt = 1, S = 0, T = 25;
for(i=1;i<=m;i++)
{
scanf(" %c %c%d", &a, &b, &x);
Add(a-'A', b-'A', x);
Add(b-'A', a-'A', 0);
}
printf("%d\n", Dinic());
return 0;
}