Description
Input
Output
Sample Input
6 9 1 2 5 2 3 5 3 1 10 3 4 12 4 1 8 4 6 11 5 4 7 5 6 9 6 5 4 6 5 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1
Sample Output
42 -1
Hint
In the first sample, there are two cycles, (1->2->3->1) and (6->5->4->6) whose length is 20 + 22 = 42.
#include<iostream> #include<cstring> #include<cstdio> #include<queue> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) using namespace std; const int mm=234; const int oo=1e9; bool vis[mm]; int head[mm],edge,work[mm],dis[mm],src,dest,node; class Edge { public:int v,next,flow,cost; }e[mm*mm*2]; void data() { clr(head,-1);edge=0; } void add(int u,int v,int _flow,int _cost) { e[edge].v=v;e[edge].flow=_flow;e[edge].cost=_cost;e[edge].next=head[u];head[u]=edge++; e[edge].v=u;e[edge].flow=0;e[edge].cost=-_cost;e[edge].next=head[v];head[v]=edge++; } bool spfa() { FOR(i,0,node)dis[i]=oo,vis[i]=0; queue<int>Q;work[src]=work[dest]=-1; Q.push(src);int u,v;dis[src]=0; while(!Q.empty()) { u=Q.front();Q.pop();vis[u]=0; for(int i=head[u];~i;i=e[i].next) { v=e[i].v; if(e[i].flow&&dis[v]>dis[u]+e[i].cost) { dis[v]=dis[u]+e[i].cost;work[v]=i^1;//path if(vis[v])continue;vis[v]=1;Q.push(v); } } } //FOR(i,0,node)printf("d=%d %d\n",i,dis[i]); return work[dest]!=-1; } int max_spfa(int& many) { int ret=0,num; while(spfa()) { num=oo;//puts("++"); for(int i=work[dest];~i;i=work[e[i].v]) { if(e[i^1].flow<num)num=e[i^1].flow; } ret+=num*dis[dest];many+=num; for(int i=work[dest];~i;i=work[e[i].v]) e[i^1].flow-=num,e[i].flow+=num; } return ret; } int n,m; int main() { int a,b,c; while(~scanf("%d%d",&n,&m)) { data();src=0;dest=n+n+1;node=n+n+2; FOR(i,1,n)add(src,i,1,0),add(i+n,dest,1,0); FOR(i,1,m) { scanf("%d%d%d",&a,&b,&c); add(a,b+n,1,c); } int ret=0,ans; ans=max_spfa(ret); //cout<<ret<<endl; if(ret==n) printf("%d\n",ans); else printf("-1\n"); } return 0; }