POJ - 2987 Firing(最大权闭合图)
生活随笔
收集整理的這篇文章主要介紹了
POJ - 2987 Firing(最大权闭合图)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:某公司想要裁員,裁員的標(biāo)準(zhǔn)是如果某人被裁,那么其下屬也會(huì)被裁,依此類(lèi)推,每一個(gè)人都有一個(gè)貢獻(xiàn)度,問(wèn)怎樣裁員才能使得最后的貢獻(xiàn)度最大并且裁掉人數(shù)最少
題目分析:最大權(quán)閉合圖的模板題,先插個(gè)眼:
大佬的博客
簡(jiǎn)單背一下結(jié)論吧:
最大權(quán)閉合圖 :原邊改為正無(wú)窮后,添加S和T,S向所有點(diǎn)連正權(quán),所有點(diǎn)向T連負(fù)權(quán)的絕對(duì)值.求最小割,用所有權(quán)值為正的點(diǎn)相加之和減掉最小割得到最大權(quán)閉合圖。
還是需要多理解理解啊,理解懂了就是一個(gè)模板題了
最后需要注意的一個(gè)小細(xì)節(jié)就是題目中給出的是有環(huán)有向圖,所以最后dfs遍歷的時(shí)候要用vis數(shù)組標(biāo)記一下,不能用v!=fa這樣的條件來(lái)判斷,會(huì)RE
代碼:
#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=5e3+100;struct Edge {int to,w,next; }edge[N*N];//邊數(shù)int head[N],cnt,tot;bool vis[N];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;//反向邊邊權(quán)設(shè)置為0edge[cnt].next=head[v];head[v]=cnt++; }int d[N],now[N];//深度 當(dāng)前弧優(yōu)化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(vis,false,sizeof(vis));memset(head,-1,sizeof(head));cnt=tot=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; }void dfs(int u) {tot++;vis[u]=true;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;if(edge[i].w>0&&!vis[v])dfs(v);} }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=N-1,ed=st-1;LL sum=0;for(int i=1;i<=n;i++){int val;scanf("%d",&val);if(val>0){sum+=val;addedge(st,i,val);}else{addedge(i,ed,-val);}}while(m--){int u,v;scanf("%d%d",&u,&v);addedge(u,v,inf);}LL ans=sum-solve(st,ed);dfs(st);printf("%d %lld\n",tot-1,ans);}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的POJ - 2987 Firing(最大权闭合图)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CodeForces - 510E Fo
- 下一篇: (转)网络流-最大流 SAP算法(模板)