poj 1149 很好的建圖思想
阿新 • • 發佈:2018-11-17
題目連結:http://poj.org/problem?id=1149
題目思路:主要就是建圖問題,推薦論文:https://wenku.baidu.com/view/0ad00abec77da26925c5b01c.html
剩下的就是網路流的模板問題了
AC程式碼
#include<queue> #include<cstring> #include<iostream> #include<set> #include<stdio.h> using namespace std; #define maxn 200 #define maxm 100000 #define inf 0x3f3f3f3f int first[maxn]; int edge_num; int lev[maxn]; int vis[maxn]; int mark[1200]; int num[1200]; struct edge{ int u,v; int cap; int next; }e[maxm]; void add_edge(int u,int v,int c) { e[edge_num].u=u; e[edge_num].v=v; e[edge_num].cap=c; e[edge_num].next=first[u]; first[u]=edge_num++; e[edge_num].u=v; e[edge_num].v=u; e[edge_num].cap=0; e[edge_num].next=first[v]; first[v]=edge_num++; } int Dinic_spath(int s,int t) { queue<int>q; q.push(s); memset(lev,-1,sizeof(lev)); memset(vis,0,sizeof(vis)); lev[s]=0; while(!q.empty()) { int u=q.front(); vis[u]=0; q.pop(); for(int k=first[u];k!=-1;k=e[k].next) { int v=e[k].v; if(lev[v]==-1&&e[k].cap>0) { lev[v]=lev[u]+1; if(!vis[v]) { vis[v]=1; q.push(v); } } } } return lev[t]!=-1; } int Dinic_dfs(int u,int t,int flow) { int cost=0; if(u==t) return flow; for(int k=first[u];k!=-1;k=e[k].next) { int v=e[k].v; if(lev[v]==lev[u]+1&&e[k].cap>0) { int minn=Dinic_dfs(v,t,min(e[k].cap,flow-cost)); if(minn>0) { e[k].cap=e[k].cap-minn; e[k^1].cap=e[k^1].cap+minn; cost+=minn; if(cost==flow) break; } else lev[v]=-1; } } return cost; } int main() { memset(first,-1,sizeof(first)); edge_num=0; memset(mark,0,sizeof(mark)); int M,N; scanf("%d%d",&M,&N); for(int i=1;i<=M;++i) scanf("%d",&num[i]); for(int i=1;i<=N;++i) { set<int>sets; int temp; scanf("%d",&temp); int temp2=0; for(int j=1;j<=temp;++j) { int x; scanf("%d",&x); if(mark[x]==0) { mark[x]=i; temp2+=num[x]; } else sets.insert(mark[x]); } scanf("%d",&temp); add_edge(i,N+1,temp); add_edge(0,i,temp2); for(set<int>::iterator pi=sets.begin();pi!=sets.end();++pi) add_edge(*pi,i,inf); sets.clear(); } int f=0; while(Dinic_spath(0,N+1)) f+=Dinic_dfs(0,N+1,inf); printf("%d\n",f); return 0; }