P2936 [USACO09JAN]全流Total Flow
也是模板题
注意:源点为A(1),终点为Z(26)。中间处理 连接边:add(u-'A'+1,v-'A'+1,w); add(v-'A'+1,u-'A'+1,0);
题目链接:https://www.luogu.com.cn/problem/P2936
#include <bits/stdc++.h> using namespace std; const int maxn=1000000+5; int to[maxn*2],last[maxn],nxt[maxn*2],wi[maxn*2],deep[maxn],cnt=-1,n,m,s,t; void add(int u,int v,int w){wi[++cnt]=w; to[cnt]=v; nxt[cnt]=last[u]; last[u]=cnt; return ;} bool bfs() { queue <int> Q; while(!Q.empty()) Q.pop(); memset(deep,0,sizeof(deep)); deep[s]=1; Q.push(s); do{ int u=Q.front(); Q.pop(); for(int i=last[u];i!=-1;i=nxt[i]) if(wi[i]>0 && deep[to[i]]==0) { deep[to[i]]=deep[u]+1; Q.push(to[i]); } }while(!Q.empty()); if(deep[t]!=0) return 1; return 0; } int dfs(int u,int dist) { if(u==t) return dist; for(int i=last[u];i!=-1;i=nxt[i]) if(deep[to[i]]==deep[u]+1 && wi[i]!=0){ int di=dfs(to[i],min(wi[i],dist)); if(di>0) { wi[i]-=di; wi[i^1]+=di; return di; } } return 0; } int dinic() { int ans=0; while(bfs()) while(int d=dfs(s,100000007)) ans+=d; return ans; } int main() { memset(nxt,-1,sizeof(nxt)); memset(last,-1,sizeof(last)); cin>>m; s=1,t=26; for(int i=1;i<=m;i++) { char u,v; int w; cin>>u>>v>>w; add(u-'A'+1,v-'A'+1,w); add(v-'A'+1,u-'A'+1,0); } cout<<dinic(); return 0; }