您的位置:首页 > 其它

hdu 3488 Tour (有向环最小权值覆盖,费用流)

2017-10-17 20:56 363 查看
题目:http://acm.split.hdu.edu.cn/showproblem.php?pid=3488

和1853一毛一样,再做一遍就是为了爽一爽,看了下评论区,秒a了。

#include<cstdio>
#include<queue>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn=200001;
const int inf=0x3f3f3f3f;
int n,m,ss,tt;
int cost[100005];
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];//判断一个点是否在队列当中(SPFA算法当中要用)
int d[maxn];//起点到d[i]的最短路径保存值
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,long long& 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+=(long long )d[t]*(long long)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 MincostMaxflow(int s,int t,int num){
int flow = 0;
long long cost=0;
while(BellmanFord(s,t,flow,cost));
return cost; //flow==num? cost:-1; //(有向环最小权值覆盖这么写)
}
}g;
int minv[210][201];
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
memset(minv,inf,sizeof(minv));
ss=0;tt=2*n+1;
g.init(2*n+2);
for(int i=1;i<=n;i++){
g.AddEdge(ss,i,1,0);
g.AddEdge(i+n,tt,1,0);
}
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(c<minv[a][b]){
g.AddEdge(a,b+n,1,c);
minv[a][b]=c;
}
}
printf("%d\n",g.MincostMaxflow(ss,tt,n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: