POJ - 2135 Farm Tour(最小费用最大流)
題目鏈接:點(diǎn)擊查看
題目大意:給出一個(gè)由n個(gè)點(diǎn)和m條邊組成的無向圖,每條邊都有權(quán)值,求點(diǎn)1->點(diǎn)n->點(diǎn)1的最短路,且要求每條路至多經(jīng)過一次,并使得途徑的權(quán)值和最小
題目分析:雖然題目要求的是最短路,但其實(shí)用最短路并不是很好處理,或許可以從點(diǎn)1跑一遍迪杰斯特拉,然后將最短路刪掉,再?gòu)狞c(diǎn)n跑一次迪杰斯特拉,答案是d1[n]+d2[1],但我懶得這樣做,很顯然可以用費(fèi)用流來解決,因?yàn)橘M(fèi)用流內(nèi)部實(shí)現(xiàn)也是根據(jù)費(fèi)用的一種最短路,放到這個(gè)題目里就相當(dāng)是最短路了,既然題目要求了每條邊只能走一次,那么我們將其流量設(shè)置為1即可,雖然是要求點(diǎn)1->點(diǎn)n->點(diǎn)1,但又因?yàn)轭}目是無向圖,所以我們不妨將其轉(zhuǎn)換為點(diǎn)1->點(diǎn)n+點(diǎn)1->點(diǎn)n的兩次權(quán)值和,只不過不允許走同一條邊兩次,這樣我們就可以直接根據(jù)費(fèi)用流建圖了:
是不是感覺這樣建邊十分巧妙,運(yùn)用費(fèi)用流的流量完美將題目的約束條件融入其中,按照上面的方法建完邊后直接跑最小費(fèi)用最大流就是答案了
代碼:
#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;//點(diǎn)const int M=4e4+100;//邊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 n,m;while(scanf("%d%d",&n,&m)!=EOF){init();int st=N-1,ed=st-1;addedge(st,1,2,0);addedge(n,ed,2,0);while(m--){int u,v,w;scanf("%d%d%d",&u,&v,&w);addedge(u,v,1,w);addedge(v,u,1,w);}printf("%d\n",solve(st,ed));}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的POJ - 2135 Farm Tour(最小费用最大流)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ - 3281 Dining(最大
- 下一篇: CodeForces - 739E Go