HDU - 4289 Control(最小割-最大流)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 4289 Control(最小割-最大流)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一張n個點m條邊的無向圖,一些恐怖分子要從點st到點ed去安裝炸彈,為了阻止他們這樣做,必須在某些點布置警察,只要恐怖分子路過警察所在的點就會被逮捕,在某個點布置警察的花費是val[i],現在要求阻止恐怖分子的行動所需要的最小花費
題目分析:轉換一下題意,就是從起點st到終點ed,每個點都有一個點權,現在若想將st和ed分離到兩個集合中,問刪除點的點權和最小是多少,這樣一來就轉換成了最小割的問題,但并不是裸的問題,最小割問題是要刪除邊,將一張圖分為兩個集合,以達到邊權之和最小,那么對于這個題目而言,我們只需要拆點就好了,將每兩個點拆成入點和出點,我們記為x和xx,1~n為入點,n+1~2*n為出點,則按照下面方式建邊:
這樣建好邊后,直接跑最大流就好了,此時需要從起點的入點跑到終點的出點,也就是st到ed+n
這里需要注意一下,對于二分圖問題,dinic不加弧優化比加了弧優化要快不少,原理不明,反向優化?
代碼:
#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=1000;struct Edge {int to,w,next; }edge[N*N];//邊數int head[N],cnt;void addedge(int u,int v,int 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*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; }int dinic(int x,int t,int flow)//更新答案 {if(x==t)return flow;int rest=flow,i;for(i=now[x];i!=-1&&rest;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(w&&d[v]==d[x]+1){int 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; }int solve(int st,int ed) {int 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 n,m;while(scanf("%d%d",&n,&m)!=EOF){init();int st,ed;scanf("%d%d",&st,&ed);for(int i=1;i<=n;i++){int val;scanf("%d",&val);addedge(i,i+n,val);}for(int i=1;i<=m;i++){int u,v;scanf("%d%d",&u,&v);addedge(u+n,v,inf);addedge(v+n,u,inf);}printf("%d\n",solve(st,ed+n));}return 0; }?
總結
以上是生活随笔為你收集整理的HDU - 4289 Control(最小割-最大流)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1265D B
- 下一篇: HDU - 3605 Escape(二分