HDU - 3987 Harry Potter and the Forbidden Forest(最小割最少边数)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 3987 Harry Potter and the Forbidden Forest(最小割最少边数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個由n個點和m條邊組成的圖,求最小割的最小邊數
題目分析:和hdu6214大同小異,都是模板題,這個題目用第一種方法,也就是先跑一遍最大流,然后修改一下殘余網絡上的權值,再跑一次最大流的方法來實現
代碼:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e3+100;const int M=4e5+100;struct Edge {int to,next;LL w; }edge[M];//邊數int head[N],cnt;void addedge(int u,int v,LL w) {edge[cnt].to=v;edge[cnt].w=w;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;//反向邊邊權設置為0edge[cnt].next=head[v];head[v]=cnt++; }int d[N],now[N];//深度 當前弧優化bool bfs(int s,int t)//尋找增廣路 {memset(d,0,sizeof(d));queue<int>q;q.push(s);now[s]=head[s];d[s]=1;while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(d[v])continue;if(!w)continue;d[v]=d[u]+1;now[v]=head[v];q.push(v);if(v==t)return true;}}return false; }LL dinic(int x,int t,LL flow)//更新答案 {if(x==t)return flow;LL rest=flow,i;for(i=now[x];i!=-1&&rest;i=edge[i].next){int v=edge[i].to;LL w=edge[i].w;if(w&&d[v]==d[x]+1){LL k=dinic(v,t,min(rest,w));if(!k)d[v]=0;edge[i].w-=k;edge[i^1].w+=k;rest-=k;}}now[x]=i;return flow-rest; }void init() {memset(head,-1,sizeof(head));cnt=0; }LL solve(int st,int ed) {LL ans=0,flow;while(bfs(st,ed))while(flow=dinic(st,ed,inf))ans+=flow;return ans; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int w;cin>>w;int kase=0;while(w--){init();int n,m;scanf("%d%d",&n,&m);while(m--){int u,v,w,t;scanf("%d%d%d%d",&u,&v,&w,&t);addedge(u,v,w);if(t)addedge(v,u,w);}solve(0,n-1);for(int i=0;i<cnt;i+=2){if(!edge[i].w)edge[i].w=1;elseedge[i].w=inf;}printf("Case %d: %lld\n",++kase,solve(0,n-1));}return 0; }?
總結
以上是生活随笔為你收集整理的HDU - 3987 Harry Potter and the Forbidden Forest(最小割最少边数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 6214 Smallest
- 下一篇: HDU - 3126 Nova(最大流+