bzoj 2502 清理雪道(有源汇的上下界最小流)
【题意】
有一个DAG,要求每条边必须经过一次,求最少经过次数。
【思路】
有上下界的最小流。
边的下界为1,上界为无穷。构造可行流模型,先不加ts边跑一遍最大流,然后加上t->s的inf边跑一遍最大流。
【代码】
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<set> 2 #include<cmath> 3 #include<queue> 4 #include<vector> 5 #include<cstdio> 6 #include<cstring> 7 #include<iostream> 8 #include<algorithm> 9 #define trav(u,i) for(int i=front[u];i;i=e[i].nxt) 10 #define FOR(a,b,c) for(int a=(b);a<=(c);a++) 11 using namespace std; 12 13 typedef long long ll; 14 const int N = 5e4+10; 15 const int inf = 1e9; 16 17 ll read() { 18 char c=getchar(); 19 ll f=1,x=0; 20 while(!isdigit(c)) { 21 if(c=='-') f=-1; c=getchar(); 22 } 23 while(isdigit(c)) 24 x=x*10+c-'0',c=getchar(); 25 return x*f; 26 } 27 28 struct Edge { 29 int u,v,cap,flow; 30 Edge(int u=0,int v=0,int cap=0,int flow=0) 31 :u(u),v(v),cap(cap),flow(flow){} 32 }; 33 struct Dinic { 34 int n,m,s,t; 35 int d[N],cur[N],vis[N]; 36 vector<int> g[N]; 37 vector<Edge> es; 38 queue<int> q; 39 void init(int n) { 40 this->n=n; 41 es.clear(); 42 FOR(i,0,n) g[i].clear(); 43 } 44 void clear() { 45 FOR(i,0,(int)es.size()-1) es[i].flow=0; 46 } 47 void AddEdge(int u,int v,int w) { 48 es.push_back(Edge(u,v,w,0)); 49 es.push_back(Edge(v,u,0,0)); 50 m=es.size(); 51 g[u].push_back(m-2); 52 g[v].push_back(m-1); 53 } 54 int bfs() { 55 memset(vis,0,sizeof(vis)); 56 q.push(s); d[s]=0; vis[s]=1; 57 while(!q.empty()) { 58 int u=q.front(); q.pop(); 59 FOR(i,0,(int)g[u].size()-1) { 60 Edge& e=es[g[u][i]]; 61 int v=e.v; 62 if(!vis[v]&&e.cap>e.flow) { 63 vis[v]=1; 64 d[v]=d[u]+1; 65 q.push(v); 66 } 67 } 68 } 69 return vis[t]; 70 } 71 int dfs(int u,int a) { 72 if(u==t||!a) return a; 73 int flow=0,f; 74 for(int& i=cur[u];i<g[u].size();i++) { 75 Edge& e=es[g[u][i]]; 76 int v=e.v; 77 if(d[v]==d[u]+1&&(f=dfs(v,min(a,e.cap-e.flow)))>0) { 78 e.flow+=f; 79 es[g[u][i]^1].flow-=f; 80 flow+=f; a-=f; 81 if(!a) break; 82 } 83 } 84 return flow; 85 } 86 int MaxFlow(int s,int t) { 87 this->s=s,this->t=t; 88 int flow=0; 89 while(bfs()) { 90 memset(cur,0,sizeof(cur)); 91 flow+=dfs(s,inf); 92 } 93 return flow; 94 } 95 } dc; 96 97 int n,m,sum,down[N],in[N],id[N],out[N],B[N]; 98 99 int main() 100 { 101 n=read(); 102 int s=0,t=n+1,S=t+1,T=S+1; 103 dc.init(T+1); 104 FOR(i,1,n) { 105 m=read(); 106 FOR(j,1,m) { 107 int x=read(); 108 dc.AddEdge(i,x,inf); 109 B[i]--,B[x]++; 110 out[i]++,in[x]++; 111 } 112 } 113 FOR(i,1,n) { 114 if(!in[i]) dc.AddEdge(s,i,inf); 115 if(!out[i]) dc.AddEdge(i,t,inf); 116 } 117 FOR(i,s,t) { 118 if(B[i]>0) dc.AddEdge(S,i,B[i]),sum+=B[i]; 119 if(B[i]<0) dc.AddEdge(i,T,-B[i]); 120 } 121 int flow=dc.MaxFlow(S,T); 122 dc.AddEdge(t,s,inf); 123 flow+=dc.MaxFlow(S,T); 124 printf("%d\n",flow); 125 return 0; 126 }
posted on 2016-03-24 16:18 hahalidaxin 阅读(630) 评论(1) 编辑 收藏 举报