日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hdu 3395(费用流,二分图的最大权匹配)

發布時間:2025/3/16 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hdu 3395(费用流,二分图的最大权匹配) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=3395

解題思路:

這個構圖很容易出錯,最開始都容易想,把每個點拆開,分為攻擊和被攻擊的,建圖如下:

源點s與攻擊的魚i建邊(s,i,1,0);

假設i攻擊j,則建邊(i,j+n,1,-val[i]^val[j]);

被攻擊的魚i與匯點建邊(i+n,t,1,0);


但這個思路是錯的,見下圖:


在這種情況下,跑出來的結果是2,但答案顯然是9。

原因很簡單,因為費用流首先保證的是最大流,在流量最大的情況下再選擇費用最優。這里顯然最大流為2,所以費用肯定是2,不可能得到9;

要保證得到最優的解,首先肯定要保證費用優先,其次再考慮最大流,這里有一個很好的解決方案:

每一條魚i與匯點t建立一條邊(i,t,1,0),即有每一條魚可以不攻擊任何魚


總結:權值最大或最小的匹配,不一定會保證是最大流,即最大流可能會把某些權值大的邊給排除掉,除非題目明確說明。

#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<vector> using namespace std;#define end() return 0typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull;const int maxn = 100 + 5; const int INF = 0x7f7f7f7f;struct Edge{int from,to,cap,flow,cost;Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} };struct MCMF{int n,m,flow,cost;vector<Edge>edge; //邊數的兩倍vector<int>G[2*maxn]; //鄰接表,G[i][j]表示i的第j條邊在e數組中的序號int inq[2*maxn]; //是否在隊列int d[2*maxn]; //Bellman-Fordint p[2*maxn]; //上一條弧int a[2*maxn]; //可改進量void init(int n){this -> n = n;for(int i=0;i<=n;i++) G[i].clear();edge.clear();}void addEdge(int from,int to,int cap,int cost){edge.push_back(Edge(from,to,cap,0,cost));edge.push_back(Edge(to,from,0,0,-cost));m=edge.size();G[from].push_back(m-2);G[to].push_back(m-1);}bool BellmanFord(int s,int t,int& flow,int& cost){memset(d,INF,sizeof(d));memset(inq,0,sizeof(inq));d[s]=0; inq[s]=1; p[s]=0; a[s]=INF;queue<int>q;q.push(s);while(!q.empty()){int u=q.front();q.pop();inq[u]=0;for(int i=0;i<G[u].size();i++){Edge& e=edge[G[u][i]];if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){d[e.to]=d[u]+e.cost;p[e.to]=G[u][i];a[e.to]=min(a[u],e.cap-e.flow);if(!inq[e.to]){q.push(e.to);inq[e.to]=1;}}}}if(d[t]==INF) return false;flow+=a[t];cost+=d[t]*a[t];for(int u=t;u!=s;u=edge[p[u]].from){edge[p[u]].flow+=a[t];edge[p[u]^1].flow-=a[t];}return true;}//需要保證初始網絡中沒有負權圈void MincostMaxflow(int s,int t){flow=0,cost=0;while(BellmanFord(s,t,flow,cost));} };int N,tail; int value[maxn]; char matrix[maxn][maxn]; MCMF mcmf;void input(){for(int i=0;i<N;i++){scanf("%d",&value[i]);}for(int i=0;i<N;i++){scanf("%s",matrix[i]);} }void createGraph(){tail=2*N+1;mcmf.init(tail+1);for(int i=0;i<N;i++){mcmf.addEdge(0,i+1,1,0);mcmf.addEdge(i+1,tail,1,0);mcmf.addEdge(i+1+N,tail,1,0);for(int j=0;j<N;j++){if(matrix[i][j]=='1'){mcmf.addEdge(i+1,j+1+N,1,-(value[i]^value[j]));}}} }void solve(){createGraph();mcmf.MincostMaxflow(0,tail);printf("%d\n",-mcmf.cost); }int main(){while(scanf("%d",&N)!=EOF&&N){input();solve();}end(); }

總結

以上是生活随笔為你收集整理的hdu 3395(费用流,二分图的最大权匹配)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。