Test instructions
FJ with friends to visit their farms, from their own house to the farm, and then return from the farm to his house, asked to go back to the same road. The number of points in the House is 1, the farm is N, there are many points between 1 and N, given n vertices, m bars, and then m rows have three numbers, the path length of a,b,c for A to C is C, and a to B is a non-edge, now requires from 1 point to N Point return from N point to 1 points of the shortest
Ideas:
Because each side can only pass once, you can set the capacity of this edge is 1, the cost is the length. Then add a source point S and a meeting point T, from S to 1 nodes with a capacity is 2 of the cost is 0 of the arc, for the meeting point T is the same, so that a minimum cost of the maximum flow of the graph has been built. However, it is important to note that the problem is given is a non-directed graph, so when the side of the building should be positive and negative two direction of the key once.
#include <iostream> #include <cstdio> #include <queue> #include <cstring> #include <
Algorithm> using namespace std;
int n,m;
const int maxn=2000+100;
const int maxm=20000+100;
const int inf=0x3f3f3f3f;
int head[maxm],cnt; struct Edge {int u,v,nxt,flow,cost;}
EDGE[MAXM*5+100];
int DIS[MAXN],PRE[MAXM],P[MAXN];
int VIS[MAXN];
void Add_edge (int u,int v,int c,int cost) {edge[cnt].u=u;
Edge[cnt].v=v;
Edge[cnt].flow=c;
Edge[cnt].cost=cost;
Edge[cnt].nxt=head[u];
head[u]=cnt++;
Edge[cnt].u=v;
Edge[cnt].v=u;
edge[cnt].flow=0;
Edge[cnt].cost=-cost;
EDGE[CNT].NXT=HEAD[V];
head[v]=cnt++;
} int SPFA (int s,int t) {queue<int>q;
memset (pre,-1,sizeof (pre));
memset (vis,0,sizeof (VIS));
memset (dis,0x3f3f3f3f,sizeof (dis));
dis[s]=0;
Vis[s]=1;
Q.push (s);
while (!q.empty ()) {int U=q.front ();
Q.pop ();
vis[u]=0;
for (int i=head[u];i!=-1;i=edge[i].nxt){int v=edge[i].v;
if (edge[i].flow&&dis[v]>dis[u]+edge[i].cost) {dis[v]=dis[u]+edge[i].cost;
Pre[v]=i;
P[v]=u;
if (!vis[v]) {vis[v]=1;
Q.push (v);
}}}} if (Pre[t]==-1) return 0;
return 1;
} int Min_cost_flow (int s,int t) {int ans_flow=0,ans_cost=0;
int U,minn;
while (SPFA (s,t)) {u=t;
Minn=inf;
for (int i=pre[u];i!=-1;i=pre[edge[i].u]) {minn=min (Edge[i].flow,minn);
} u=t;
for (int i=pre[u];i!=-1;i=pre[edge[i].u]) {Edge[i].flow-=minn;
Edge[i^1].flow+=minn;
Ans_cost+=edge[i].cost;
} Ans_flow+=minn;
if (ans_flow==2) {return ans_cost;
}} return ans_cost; } int main () {scanf ("%d%d", &n,&m);
memset (head,-1,sizeof (head));
cnt=0;
Add_edge (0,1,2,0);
Add_edge (n,n+1,2,0);
while (m--) {int xx,yy,zz;
scanf ("%d%d%d", &xx,&yy,&zz);
Add_edge (XX,YY,1,ZZ);
Add_edge (YY,XX,1,ZZ);
} printf ("%d\n", Min_cost_flow (0,n+1)); }