标签:bfs queue plm turn rom res ever visit cto
Description
Input
Output
Sample Input
4 5 8 2 1 0 1 3 0 4 1 1 1 5 0 5 4 1 3 4 0 4 2 1 2 2 0 4 4 1 2 1 2 3 0 3 4 0 1 4 1 3 3 1 2 0 2 3 0 3 2 0 3 4 1 2 0 2 3 1 1 2 0 3 2 0
Sample Output
possible impossible impossible possible
#include<cstdio> #include<vector> #include<queue> #include<cstring> using namespace std; const int INF=0x3f3f3f3f,MAXN=205; int in[MAXN],out[MAXN],m,s; struct Edge { int from,to,cap,flow; Edge(){} Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}; }; struct dinic { int s,t; vector<Edge>edges; vector<int>G[MAXN]; bool vis[MAXN]; int d[MAXN]; int cur[MAXN]; void init() { for(int i=0;i<=m+1;i++)G[i].clear(); edges.clear(); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); } 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 m=edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool bfs() { memset(vis,0,sizeof(vis)); queue<int>q; q.push(s); d[s]=0; vis[s]=1; while(!q.empty()) { int x=q.front();q.pop(); for(int i=0;i<G[x].size();i++) { Edge& e=edges[G[x][i]]; if(!vis[e.to]&&e.cap>e.flow) { vis[e.to]=1; d[e.to]=d[x]+1; q.push(e.to); } } } return vis[t]; } int dfs(int x,int a) { if(x==t||a==0)return a; int flow=0,f; for(int& i=cur[x];i<G[x].size();i++) { Edge& e=edges[G[x][i]]; if(d[x]+1==d[e.to]&&(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 s,int t) { this->s=s,this->t=t; int flow=0; while(bfs()) { memset(cur,0,sizeof(cur)); flow+=dfs(s,INF); } return flow; } }dc; int main() { int T; scanf("%d",&T); while(T--) { dc.init(); scanf("%d%d",&m,&s); for(int i=0;i<s;i++) { int u,v,d; scanf("%d%d%d",&u,&v,&d); out[u]++,in[v]++; if(d==0)dc.addedge(u,v,1); } bool ok=1; int sum=0; for(int i=1;i<=m;i++) if((in[i]-out[i])%2==1) { ok=0; break; } if(!ok){puts("impossible");continue;} for(int i=1;i<=m;i++) { if(in[i]<out[i]) dc.addedge(0,i,(out[i]-in[i])/2); else if(in[i]>out[i]) { dc.addedge(i,m+1,(in[i]-out[i])/2); sum+=(in[i]-out[i])/2; } } puts(sum==dc.maxflow(0,m+1)?"possible":"impossible"); } return 0; }
POJ 1637 Sightseeing tour (混合图欧拉回路)
标签:bfs queue plm turn rom res ever visit cto
原文地址:http://www.cnblogs.com/homura/p/6075619.html