http://acm.hdu.edu.cn/showproblem.php?pid=3488
题意:
给出n个点和m条边,每条边有距离,把这n个点分成1个或多个环,且每个点只能在一个环中,保证有解。
思路:
把一个点分成两部分,1~n和n+i~2*n。
连边的情况是这样的,(src,i,1,0),(i+n,dst,1,0)。
如果两个点之间相同,则(i,j+n,1,d)。
其实这道题目就是选n条边,如何使得权值之和最小。
具体请参考这http://blog.****.net/u013480600/article/details/39185013
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
typedef long long LL; const int maxn=+;
const int INF=0x3f3f3f3f; 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;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn]; void init(int n)
{
this->n = n;
for (int i = ; i<n; i++) G[i].clear();
edges.clear();
} void AddEdge(int from, int to, int cap, int cost)
{
edges.push_back(Edge(from, to, cap, , cost));
edges.push_back(Edge(to, from, , , -cost));
m = edges.size();
G[from].push_back(m - );
G[to].push_back(m - );
} bool BellmanFord(int s, int t, int &flow, LL & cost)
{
for (int i = ; i<n; i++) d[i] = INF;
memset(inq, , sizeof(inq));
d[s] = ; inq[s] = ; p[s] = ; a[s] = INF; queue<int> Q;
Q.push(s);
while (!Q.empty()){
int u = Q.front(); Q.pop();
inq[u] = ;
for (int i = ; i<G[u].size(); i++){
Edge& e = edges[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] = ; }
}
}
}
if (d[t] == INF) return false;
flow += a[t];
cost += (LL)d[t] * (LL)a[t];
for (int u = t; u != s; u = edges[p[u]].from){
edges[p[u]].flow += a[t];
edges[p[u] ^ ].flow -= a[t]; }
return true;
} void MincostMaxdflow(int s, int t, LL & cost)
{
int flow = ; cost = ;
while (BellmanFord(s, t, flow, cost) );
//return flow;
}
}t; int n,m; int main()
{
//freopen("D:\\input.txt", "r", stdin);
int T;
scanf("%d",&T);
int u,v,d;
while(T--)
{
scanf("%d%d",&n,&m);
int src=,dst=*n+;
t.init(dst+);
for(int i=;i<=n;i++)
{
t.AddEdge(src,i,,);
t.AddEdge(i+n,dst,,);
}
for(int i=;i<m;i++)
{
scanf("%d%d%d",&u,&v,&d);
t.AddEdge(u,v+n,,d);
}
long long cost;
t.MincostMaxdflow(src,dst,cost);
printf("%d\n",cost);
}
return ;
}