Admiral UVA - 1658
题意:
给你一个 有v个点的,有e条边的有向加权图,求 1-v 的两条不相交(除了起点和终点外)的路径,使得权和最小。
思路:
- 由于要限制,不相交,可以拆点,保证一个点只被经过一次。(除了终点以外)
- 跑最小费用流,且流量为2.
反思:
一开始拆点的时候,连边的时候有一个逻辑错误。
AC
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <queue>
#define mst(x,a) memset(x,a,sizeof(x))
#define sz(a) ((int)a.size())
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
#define pb push_back
#define fzhead EDGE(int u, int v, int c, int f, int w)
#define fzbody from(u), to(v), cap(c), flow(f), cost(w)
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 3000+10;
struct EDGE{
int from, to, cap, flow, cost;
EDGE(){}
fzhead:fzbody{}
};
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;
fori(i,0,n)G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap, int cost){
edges.pb({from, to, cap, 0, cost});
edges.pb({to, from, 0, 0, -cost});
m = edges.size();
G[from].pb(m-2);
G[to].pb(m-1);
}
bool BellmanFord(int s, int t, int& flow, long long& cost){
fori(i,0,n)d[i] = INF;
mst(inq,0);
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;
fori(i,0,sz(G[u])){
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, long long&cost){
int flow = 0; cost = 0;
while(BellmanFord(s,t,flow,cost))if(flow>=2)return flow;//if(flow == 2);
return flow;
}
}mcmf;
int n, m;
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
while(cin>>n>>m){
int u, v;
long long cost;
mcmf.init(maxn);
int s=1,t=n;
fori(i,2,n)mcmf.AddEdge(i, i+n, 1, 0);
For(i,1,m){
cin>>u>>v>>cost;
if(u != t && u != s){
//mcmf.AddEdge(u, u + n, 1, 0);
u=u+n;///mcmf.AddEdge(u + n, v, 1, cost);
}///else mcmf.AddEdge(u, v, 1, cost);
//else mcmf.AddEdge(u + n, v, 1, cost);
/// if(v!=s&&v!=t)mcmf.AddEdge(v, v + n, 1, 0);
mcmf.AddEdge(u, v, 1, cost);
}
mcmf.MincostMaxflow(s, t, cost);
cout<<cost<<endl;
}
return 0;
}