构建超级源点跟超级汇点,源点跟汇点所连接的值就是用户跟发电厂的值
解决最大流的流程:
分析题意,建立模型,构造网络,解决问题。
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define N 110
int e[N][N];
int S,T;
int n,np,nc,m;
int d[N];
bool bfs(){
memset(d,-1,sizeof(d));
queue<int> q;
q.push(S);
d[S]=0;
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=0;i<n;i++){
if(e[u][i]&&d[i]==-1){
d[i]=d[u]+1;
q.push(i);
}
}
}
return d[T]!=-1;
}
int dfs(int u,int flow){
if(u==T){
return flow;
}
int res=0;
for(int i=0;i<n;i++){
if(e[u][i]&&d[i]==d[u]+1){
int tmp=dfs(i,min(flow,e[u][i]));
flow-=tmp;
e[u][i]-=tmp;
res+=tmp;
e[i][u]+=tmp;
if(flow==0) break;
}
}
if(res==0) d[u]=-1;
return res;
}
int dinic(){
int res=0;
while(bfs()){
res+=dfs(S,INF);
}
return res;
}
//#define debug
int main(){
#ifdef debug
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#endif // debug
int x,y,z;
char s[10];
while(scanf("%d%d%d%d",&n,&np,&nc,&m)!=EOF){
memset(e,0,sizeof(e));
while(m--){
scanf("%s",s);
sscanf(s,"(%d,%d)%d",&x,&y,&z);
if(x==y) continue;
e[x][y]+=z;
}
for(int i=0;i<np;i++){
scanf("%s",s);
sscanf(s,"(%d)%d",&x,&y);
e[n][x]=y;
}
for(int i=0;i<nc;i++){
scanf("%s",s);
sscanf(s,"(%d)%d",&x,&y);
e[x][n+1]=y;
}
S=n;
T=n+1;
n+=2;
printf("%d\n",dinic());
}
return 0;
}