标签:log iostream open nes const pen sam pos getchar
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 3159 Accepted Submission(s): 1525
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; typedef long long ll; const int N=505,M=1e5,INF=1e9; inline int read(){ char c=getchar();int x=0,f=1; while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1; c=getchar();} while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘; c=getchar();} return x*f; } int n,m,u,v,w,s,t; struct edge{ int v,ne,c,f,w; }e[M<<1]; int cnt,h[N]; inline void ins(int u,int v,int c,int w){ cnt++; e[cnt].v=v;e[cnt].c=c;e[cnt].f=0;e[cnt].w=w; e[cnt].ne=h[u];h[u]=cnt; cnt++; e[cnt].v=u;e[cnt].c=0;e[cnt].f=0;e[cnt].w=-w; e[cnt].ne=h[v];h[v]=cnt; } int d[N],pre[N],pos[N],q[N],head=1,tail=1,inq[N]; inline void lop(int &x){if(x==N) x=1;else if(x==0) x=N-1;} bool spfa(){ memset(d,127,sizeof(d)); d[s]=0;pre[t]=-1; head=tail=1; memset(inq,0,sizeof(inq)); q[tail++]=s;inq[s]=1; while(head!=tail){ int u=q[head++];lop(head);inq[u]=0; for(int i=h[u];i;i=e[i].ne){ int v=e[i].v,w=e[i].w; if(d[v]>d[u]+w&&e[i].c>e[i].f){ d[v]=d[u]+w; pre[v]=u; pos[v]=i; if(!inq[v]){ if(d[v]<d[q[head]]) head--,lop(head),q[head]=v; else q[tail++]=v,lop(tail); inq[v]=1; } } } } return pre[t]==-1?0:1; } int mcmf(){ int flow=0,cost=0; while(spfa()){ int f=INF; for(int i=t;i!=s;i=pre[i]) f=min(f,e[pos[i]].c-e[pos[i]].f); flow+=f; cost+=f*d[t]; for(int i=t;i!=s;i=pre[i]){ e[pos[i]].f+=f; e[((pos[i]-1)^1)+1].f-=f; } } return cost; } int g[N][N]; int main(){ //freopen("in.txt","r",stdin); int T=read(); while(T--){ cnt=0; memset(h,0,sizeof(h)); n=read();m=read();s=0;t=n+n+1; for(int i=1;i<=n;i++){ ins(s,i,1,0),ins(n+i,t,1,0); for(int j=1;j<=n;j++) g[i][j]=INF; } for(int i=1;i<=m;i++) u=read(),v=read(),w=read(),g[u][v]=min(g[u][v],w); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(g[i][j]<INF) ins(i,j+n,1,g[i][j]); printf("%d\n",mcmf()); } }
标签:log iostream open nes const pen sam pos getchar
原文地址:http://www.cnblogs.com/candy99/p/6347825.html