1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #include<iostream> #include<cstring> #include<queue> #include<algorithm> #include<stdio.h> using namespace std;
const int inf=0x3f3f3f3f; const int N=1010; int dis[N],pre[N],preve[N]; int n,m; struct edge{ int to,cost,capacity,rev; edge(int a,int b,int c,int d){ to=a;cost=b;capacity=c;rev=d; } }; vector<edge> e[N]; void addedge(int from,int to,int cost,int capacity){ e[from].push_back(edge(to,cost,capacity,e[to].size())); e[to].push_back(edge(from,-cost,0,e[from].size()-1)); } bool spfa(int s,int t,int cnt) { bool inq[N]; memset(pre,-1,sizeof(pre)); for(int i=1;i<=cnt;i++){ dis[i]=inf;inq[i]=false; } dis[s]=0; queue<int> Q; Q.push(s); inq[s]=true; while(!Q.empty()) { int u=Q.front(); Q.pop(); inq[u]=false; for(int i=0;i<e[u].size();i++) if(e[u][i].capacity>0){ int v=e[u][i].to,cost=e[u][i].cost; if(dis[u]+cost<dis[v]){ dis[v]=dis[u]+cost; pre[v]=u; preve[v]=i; if(!inq[v]){ inq[v]=true; Q.push(v); } } } } return dis[t]!=inf; } int mincost(int s,int t,int cnt) { int cost=0; while(spfa(s,t,cnt)) { int v=t,flow=inf; while(pre[v]!=-1){ int u=pre[v],i=preve[v]; flow=min(flow,e[u][i].capacity); v=u; } v=t; while(pre[v]!=-1) { int u=pre[v],i=preve[v]; e[u][i].capacity-=flow; e[v][e[u][i].rev].capacity+=flow; v=u; } cost+=dis[t]*flow; } return cost; } int main() { while(~scanf("%d%d",&n,&m)) { for(int i=0;i<N;i++) e[i].clear(); for(int i=1;i<=m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); addedge(u,v,w,1); addedge(v,u,w,1); } int s=n+1,t=n+2; addedge(s,1,0,2); addedge(n,t,0,2); printf("%d\n",mincost(s,t,n+2)); } return 0; }
|