题目大意:给定一张无向图,可能有重边,n个城市,m条路,问一个人从1到n再回到1并且不能走过痛一条路两次,问最小费用是多少;
题目解析:构图,源(容量为2,费用为0)->城市(容量为一,费用为cost)->汇(容量为2,费用为1);
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
const int MAXN = 1010;
const int MAXM = 100000;
const int INF = 0x3fffffff;
struct Edge
{
int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXM],tol;
int pre[MAXM],dis[MAXM];
bool vis[MAXM];
int start, end;
void init()
{
tol = 0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int> q;
for(int i = 0; i < MAXM; i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] + edge[i].cost )
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)
{
return false;
}
else
return true;
}
int minCostMaxflow(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}
int n,m;
int graph[MAXN][MAXN];
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
memset(graph,-1,sizeof(graph));
for(int i=1;i<=m;i++)
{
int u,v,l;
scanf("%d%d%d",&u,&v,&l);
addedge(u,v,1,l);
addedge(v,u,1,l);
}
start=0;
end=n+1;
addedge(0,1,2,0);
addedge(n,n+1,2,0);
int ans;
int t=minCostMaxflow(0,n+1,ans);
printf("%d\n",ans);
}
return 0;
}