SGU 176 有源汇上下界的最小流
题意:n个节点,m条路径,接下来m行a,b,c,d,假设d等于1,则a到b的流量必须为c,假设d等于0。流量能够为0到c。问假设有可行流,最小流量和每条边的流量
思路:最小流的解法与其它的不同,我们先将其变成无源汇的做法,建立超级源点和汇点,然后跑最大流。之后在加上汇点到源点的inf边。再跑最大流,假设满流则说明有解,不然无解,而最小的流量就是汇点到源点跑得流量,证明很抱歉并不会........有神犇会的话求赐教
#include <queue> #include <vector> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> #include <functional> using namespace std; typedef long long ll; const int inf=0x3f3f3f3f; const int maxn=150; struct edge{ int to,cap,rev; edge(int a,int b,int c){to=a;cap=b;rev=c;} }; vector<edge>G[maxn]; int level[maxn],iter[maxn]; void add_edge(int from,int to,int cap){ G[from].push_back(edge(to,cap,G[to].size())); G[to].push_back(edge(from,0,G[from].size()-1)); } void bfs(int s){ memset(level,-1,sizeof(level)); queue<int>que;level[s]=0; que.push(s); while(!que.empty()){ int v=que.front();que.pop(); for(unsigned int i=0;i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[e.to]<0){ level[e.to]=level[v]+1; que.push(e.to); } } } } int dfs(int v,int t,int f){ if(v==t) return f; for(int &i=iter[v];i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[v]<level[e.to]){ int d=dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap-=d; G[e.to][e.rev].cap+=d; return d; } } } return 0; } int max_flow(int s,int t){ int flow=0; while(1){ bfs(s); if(level[t]<0) return flow; memset(iter,0,sizeof(iter)); int f; while((f=dfs(s,t,inf))>0) flow+=f; } } int L[10010],R[10010],num[10010][2]; int main(){ int n,m,a,b,d,c; while(scanf("%d%d",&n,&m)!=-1){ for(int i=0;i<maxn;i++) G[i].clear(); int sum=0,S=n+1,T=n+2; for(int i=0;i<m;i++){ scanf("%d%d%d%d",&a,&b,&c,&d); if(d==1){ L[i]=c;R[i]=c; }else{ L[i]=0,R[i]=c; } add_edge(a,b,R[i]-L[i]); sum+=L[i]; num[i][0]=a;num[i][1]=G[a].size()-1; add_edge(S,b,L[i]);add_edge(a,T,L[i]); } int ans=max_flow(S,T); add_edge(n,1,inf); int kk=G[1].size()-1; int ans1=max_flow(S,T); if(ans+ans1!=sum) printf("Impossible\n"); else{ printf("%d\n",G[1][kk].cap); for(int i=0;i<m-1;i++){ printf("%d ",R[i]-G[num[i][0]][num[i][1]].cap); } printf("%d\n",R[m-1]-G[num[m-1][0]][num[m-1][1]].cap); } } return 0; }