您的位置:首页 > 其它

HDU 3435 A new Graph Game(最小费用流:有向环权值最小覆盖)

2017-04-12 07:59 369 查看
http://acm.hdu.edu.cn/showproblem.php?pid=3435

题意:
有n个点和m条边,你可以删去任意条边,使得所有点在一个哈密顿路径上,路径的权值得最小。

思路:

费用流,注意判断重边,否则会超时。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
typedef long long LL;

const int maxn=2000+5;
const int INF=0x3f3f3f3f;

int map[maxn][maxn];

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 = 0; 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, 0, cost));
edges.push_back(Edge(to, from, 0, 0, -cost));
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}

bool BellmanFord(int s, int t, int &flow, LL & cost)
{
for (int i = 0; i<n; i++) d[i] = INF;
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 = 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] = 1; }
}
}
}
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] ^ 1].flow -= a[t];

}
return true;
}

int MincostMaxdflow(int s, int t, LL & cost)
{
int flow = 0; cost = 0;
while (BellmanFord(s, t, flow, cost) );
return flow;
}
}t;

int n,m;

int main()
{
//freopen("D:\\input.txt", "r", stdin);
int T;
int kase=0;
scanf("%d",&T);
int u,v,d;
while(T--)
{
memset(map,0,sizeof(map));
scanf("%d%d",&n,&m);
int src=0,dst=2*n+1;
t.init(dst+1);
for(int i=1;i<=n;i++)
{
t.AddEdge(src,i,1,0);
t.AddEdge(i+n,dst,1,0);
}
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&d);
if(map[u][v]==0 || map[u][v]>d)
{
t.AddEdge(u,v+n,1,d);
t.AddEdge(v,u+n,1,d);
map[u][v]=map[v][u]=d;
}
}
long long cost;
int flow=t.MincostMaxdflow(src,dst,cost);
printf("Case %d: ",++kase);
if(flow==n)  printf("%d\n",cost);
else printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: