标签:
http://www.cnblogs.com/jianglangcaijin/archive/2012/09/24/2700509.html
思路:
S->0 流量为K费用0
0->i 流量为inf,费用为a[0][i]
0->T 流量为K,费用0
i->i+n 流量为1,费用为-inf
i+n->T 流量为1,费用为a[0][i]
1 #include<algorithm> 2 #include<cstdio> 3 #include<cmath> 4 #include<cstring> 5 #include<iostream> 6 #define inf 1000000 7 int a[505][505],K; 8 int tot,go[200005],next[200005],first[200005],cost[200005],flow[200005]; 9 int op[200005],dis[200005],c[200005],vis[200005],edge[200005],from[200005]; 10 int S,T,n,m,ans; 11 int read(){ 12 char ch=getchar();int t=0,f=1; 13 while (ch<‘0‘||ch>‘9‘){if (ch==‘-‘) f=-1;ch=getchar();} 14 while (‘0‘<=ch&&ch<=‘9‘){t=t*10+ch-‘0‘;ch=getchar();} 15 return t*f; 16 } 17 void insert(int x,int y,int z,int l){ 18 tot++; 19 go[tot]=y; 20 next[tot]=first[x]; 21 first[x]=tot; 22 flow[tot]=z; 23 cost[tot]=l; 24 } 25 void add(int x,int y,int z,int l){ 26 insert(x,y,z,l);op[tot]=tot+1; 27 insert(y,x,0,-l);op[tot]=tot-1; 28 } 29 bool spfa(){ 30 for (int i=0;i<=T;i++) 31 dis[i]=0x3f3f3f3f,vis[i]=0; 32 int h=1,t=1;c[1]=S;vis[S]=1;dis[S]=0; 33 while (h<=t){ 34 int now=c[h++]; 35 for (int i=first[now];i;i=next[i]){ 36 int pur=go[i]; 37 if (dis[pur]>dis[now]+cost[i]&&flow[i]){ 38 dis[pur]=dis[now]+cost[i]; 39 edge[pur]=i; 40 from[pur]=now; 41 if (vis[pur]) continue; 42 vis[pur]=1; 43 c[++t]=pur; 44 } 45 } 46 vis[now]=0; 47 } 48 return dis[T]!=0x3f3f3f3f; 49 } 50 void updata(){ 51 int mn=0x3f3f3f3f; 52 for (int i=T;i!=S;i=from[i]){ 53 mn=std::min(mn,flow[edge[i]]); 54 } 55 for (int i=T;i!=S;i=from[i]){ 56 ans+=mn*cost[edge[i]]; 57 flow[edge[i]]-=mn; 58 flow[op[edge[i]]]+=mn; 59 } 60 } 61 int main(){ 62 while (scanf("%d",&n)!=EOF){ 63 m=read();K=read(); 64 if (n==0&&K==0&&m==0) return 0; 65 for (int i=0;i<=T;i++) first[i]=0;tot=0; 66 S=2*n+1;T=S+1; 67 for (int i=0;i<=n;i++) 68 for (int j=0;j<=n;j++) 69 if (i==j) a[i][j]=0; 70 else a[i][j]=0x3f3f3f3f; 71 while(m--){ 72 int u=read(),v=read(),w=read(); 73 a[u][v]=std::min(a[u][v],w); 74 a[v][u]=std::min(a[v][u],w); 75 } 76 for (int k=0;k<=n;k++) 77 for (int i=0;i<=n;i++) 78 for (int j=0;j<=n;j++) 79 a[i][j]=std::min(a[i][j],a[i][k]+a[k][j]); 80 add(S,0,K,0); 81 add(0,T,K,0); 82 for (int i=1;i<=n;i++) 83 if (a[0][i]<0x3f3f3f3f) 84 add(0,i,inf,a[0][i]); 85 for (int i=1;i<=n;i++) 86 for (int j=i+1;j<=n;j++) 87 if (a[i][j]<0x3f3f3f3f) 88 add(i+n,j,1,a[i][j]); 89 for (int i=1;i<=n;i++) 90 if (a[0][i]<0x3f3f3f3f) 91 add(i+n,T,1,a[0][i]); 92 for (int i=1;i<=n;i++) 93 add(i,i+n,1,-inf); 94 ans=inf*n; 95 while (spfa()) updata(); 96 printf("%d\n",ans); 97 } 98 }
标签:
原文地址:http://www.cnblogs.com/qzqzgfy/p/5615339.html