SPOJ - TOURS Travelling tours(最小费用最大流)
生活随笔
收集整理的這篇文章主要介紹了
SPOJ - TOURS Travelling tours(最小费用最大流)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出一張由n個(gè)點(diǎn)和m條邊構(gòu)成的無向圖,現(xiàn)在要求將n個(gè)點(diǎn)劃分到至少一個(gè)環(huán)中去,每個(gè)環(huán)至少由兩個(gè)點(diǎn)組成,輸出最小權(quán)值和
題目分析:因?yàn)榭吹綄⒄麖垐D分為不相交的數(shù)個(gè)環(huán),不難想到二分圖的完備匹配一定會(huì)出現(xiàn)答案,有點(diǎn)最小路徑覆蓋的意思,不過當(dāng)然不能直接跑匈牙利了,因?yàn)轭}目保證了給出的圖一定滿足二分圖完備匹配,所以直接跑二分圖最大匹配的話,可以跑出答案,但并不是最優(yōu)解,故為了讓花費(fèi)最小,我們可以用最小費(fèi)用最大流來跑二分圖最大匹配,拆點(diǎn)建邊直接跑模板就是答案了
代碼:
#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=510;//點(diǎn)const int M=N*N;//邊struct Edge {int to,w,cost,next; }edge[M];int head[N],cnt;void addedge(int u,int v,int w,int cost) {edge[cnt].to=v;edge[cnt].w=w;edge[cnt].cost=cost;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;edge[cnt].cost=-cost;edge[cnt].next=head[v];head[v]=cnt++; }int d[N],incf[N],pre[N];bool vis[N];bool spfa(int s,int t) {memset(d,inf,sizeof(d));memset(vis,false,sizeof(vis));memset(pre,-1,sizeof(pre));queue<int>q;q.push(s);vis[s]=true;incf[s]=inf;d[s]=0;while(!q.empty()){int u=q.front();q.pop();vis[u]=false;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;int cost=edge[i].cost;if(!w)continue;if(d[v]>d[u]+cost){d[v]=d[u]+cost;pre[v]=i;incf[v]=min(incf[u],w);if(!vis[v]){vis[v]=true;q.push(v);}}}}return pre[t]!=-1; }int update(int s,int t) {int x=t;while(x!=s){int i=pre[x];edge[i].w-=incf[t];edge[i^1].w+=incf[t];x=edge[i^1].to;}return d[t]*incf[t]; }void init() {memset(head,-1,sizeof(head));cnt=0; }int solve(int st,int ed) {int ans=0;while(spfa(st,ed))ans+=update(st,ed);return ans; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int w;cin>>w;while(w--){init();int n,m,st=N-1,ed=st-1;scanf("%d%d",&n,&m);while(m--){int u,v,w;scanf("%d%d%d",&u,&v,&w);addedge(u,v+n,1,w);}for(int i=1;i<=n;i++){addedge(st,i,1,0);addedge(i+n,ed,1,0);}printf("%d\n",solve(st,ed));}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的SPOJ - TOURS Travelling tours(最小费用最大流)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LightOJ - 1071 Baker
- 下一篇: 洛谷 - P3980 [NOI2008]