hdu Crazy Circuits
Crazy Circuits
题目:
给出一个电路板,从+极出发到负极。
如今给你电路板上的最小电流限制,要你在电流平衡的时候求得从正极出发的最小电流。
算法:
非常裸的有源汇最小流。安有源汇最大流做法后,先求出最大流。然后。通过加入 t-->s 容量INF,是其变成一个无源汇最小流问题。这样在跑一次最大流就是结果了。尽管没有严格证明是否正确,可是我用到如今,还没发现有错误的算法。
做题时in[]忘记清空了。找了半个小时!!!
/* //!!!!!!!!!!!!!! 一定要注意清空初始化问题。!。!!。!。 */ #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <map> #include <cstdio> #include <cmath> #include <cstring> using namespace std; const int INF = 1 << 25; const int MAXN = 100 + 10; /////////////////////////////////// struct Edge{ int from,to,cap,flow,cost; Edge(){}; Edge(int _from,int _to,int _cap,int _flow) :from(_from),to(_to),cap(_cap),flow(_flow){}; }; vector<Edge> edges; vector<int> G[MAXN]; int cur[MAXN],d[MAXN]; bool vst[MAXN]; int src,sink,ss,tt; //////////////////////////////////////////// int N,M; int low[MAXN+MAXN],in[MAXN]; void init(){ ss = N + 2; tt = ss + 1; src = tt + 1; sink = src + 1; for(int i = 0;i <= sink;++i) G[i].clear(); edges.clear(); } void getId(char *str1,char *str2,int& x,int& y){ if(str1[0] == '+'){ x = ss; } else if(str1[0] == '-'){ x = tt; } else { sscanf(str1,"%d",&x); } if(str2[0] == '+'){ y = ss; } else if(str2[0] == '-'){ y = tt; } else { sscanf(str2,"%d",&y); } } void addEdge(int from,int to,int cap){ edges.push_back(Edge(from,to,cap,0)); edges.push_back(Edge(to,from,0,0)); int sz = edges.size(); G[from].push_back(sz - 2); G[to].push_back(sz - 1); } bool BFS(){ memset(vst,0,sizeof(vst)); queue<int> Q; Q.push(src); vst[src] = 1; d[src] = 0; while(!Q.empty()){ int x = Q.front(); Q.pop(); for(int i = 0;i < (int)G[x].size();++i){ Edge& e = edges[G[x][i]]; if(!vst[e.to] && e.cap > e.flow){ vst[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vst[sink]; } int DFS(int x,int a){ if(x == sink||a == 0) return a; int flow = 0,f; for(int& i = cur[x];i < (int)G[x].size();++i){ Edge& e = edges[G[x][i]]; if(d[e.to] == d[x] + 1&&(f = DFS(e.to,min(a,e.cap - e.flow))) > 0){ e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int maxFlow(){ int flow = 0; while(BFS()){ memset(cur,0,sizeof(cur)); flow += DFS(src,INF); } return flow; } int main() { while(scanf("%d%d",&N,&M),(N||M)){ init(); //!!!!!!!!!!!!! int x,y; char str1[10],str2[10]; memset(in,0,sizeof(in)); //!!!!!!!!!!!!!!!!!! for(int i = 0;i < M;++i){ scanf("%s%s%d",str1,str2,&low[i]); //printf("%s %s\n",str1,str2); getId(str1,str2,x,y); //printf("%d --> %d\n",x,y); addEdge(x,y,INF - low[i]); //有下界,没有上界 in[x] -= low[i]; in[y] += low[i]; } if(N == 0){ printf("%d\n",*max_element(low,low + M)); continue; } int sum = 0; for(int i = 1;i <= tt;++i){ if(in[i] > 0){ sum += in[i]; addEdge(src,i,in[i]); } else { addEdge(i,sink,-in[i]); } } sum -= maxFlow(); addEdge(tt,ss,INF); //转换成无源汇网络流 int flow = maxFlow(); if(sum != flow){ puts("impossible"); } else { int sz = edges.size(); printf("%d\n",edges[sz - 2].flow); } } return 0; }