3396: [Usaco2009 Jan]Total flow 水流
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 304 Solved: 134
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
Source
Silver
转一下数字,直接最大流。。
注意好像有小写字母。。
附上本蒟蒻的代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define T 26
int n,h[490001],dis[490001],head,tail,ans,sum,cnt=1,q[490001];
struct kx
{
int to,next,v;
}edge[490001];
int read()
{
int w=0,c=1;
char ch=getchar();
while (ch<'0' || ch>'9')
{
if (ch=='-') c=-1;
ch=getchar();
}
while (ch>='0' && ch<='9')
w=w*10+ch-'0',ch=getchar();
return w*c;
}
void add(int u,int v,int w)
{
cnt++,edge[cnt].next=h[u],h[u]=cnt,edge[cnt].to=v,edge[cnt].v=w;
}
bool bfs()
{
int j,p;
memset(dis,-1,sizeof(dis));
q[1]=1,dis[1]=0;
head=0,tail=1;
while (head<tail)
{
head++,j=q[head],p=h[j];
while (p)
{
if (dis[edge[p].to]<0 && edge[p].v>0)
dis[edge[p].to]=dis[j]+1,tail++,q[tail]=edge[p].to;
p=edge[p].next;
}
}
if (dis[T]>0)
return true;
else
return false;
}
int dfs(int x,int f)
{
int w,used=0,i=h[x];
if (x==T)
return f;
while (i)
{
if (edge[i].v && dis[edge[i].to]==dis[x]+1)
{
w=f-used,w=dfs(edge[i].to,min(w,edge[i].v));
edge[i].v-=w,edge[i^1].v+=w,used+=w;
if (used==f) return f;
}
i=edge[i].next;
}
if (!used) dis[x]=-1;
return used;
}
int main()
{
char s[3];
int i,u,v,flow;
n=read();
for (i=1;i<=n;i++)
{
scanf("%s",&s);
if (s[0]>='A' && s[0]<='Z')
u=s[0]-'A'+1;
else
u=s[0]-'a'+27;
scanf("%s",&s);
if (s[0]>='A' && s[0]<='Z')
v=s[0]-'A'+1;
else
v=s[0]-'a'+27;
flow=read();
add(u,v,flow);
add(v,u,0);
}
ans=0;
while (bfs())
while (sum=dfs(1,0x7fffffff))
ans+=sum;
printf("%d",ans);
return 0;
}