1 条题解
-
0
C++ :
#include <bits/stdc++.h> using namespace std; const int maxn=500+5; const int INF=0x3f3f3f3f; template<typename T> inline T read(T&x){ x=0;int _f=0;char ch=getchar(); while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar(); while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); return x=_f?-x:x; } struct Edge{ int from,to,cap,flow,cost; Edge(){} Edge(int f,int t,int c,int fl,int co):from(f),to(t),cap(c),flow(fl),cost(co){} }; struct MCMF{ int n,m,s,t,k; vector<Edge> edges; vector<int> G[maxn]; bool inq[maxn]; int d[maxn]; int p[maxn]; int a[maxn]; void init(int n,int s,int t,int k){ this->n=n, this->s=s, this->t=t, this->k=k; edges.clear(); for(int i=0;i<=n;++i) G[i].clear(); } void AddEdge(int from,int to,int cap,int cost){ edges.push_back(Edge(from,to,cap,0,cost)); edges.push_back(Edge(to,from,0,0,-cost)); m=edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool SPFA(int &flow,int &cost){ for(int i=0;i<n;++i) d[i]=INF; queue<int> Q; memset(inq,0,sizeof(inq)); d[s]=0, Q.push(s), a[s]=INF, p[s]=0, inq[s]=true; while(!Q.empty()){ int u=Q.front(); Q.pop(); inq[u]=false; for(int i=0;i<G[u].size();++i){ Edge &e=edges[G[u][i]]; if(e.cap>e.flow && d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; p[e.to]=G[u][i]; a[e.to]=min(a[u],e.cap-e.flow); if(!inq[e.to]){ Q.push(e.to); inq[e.to]=true; } } } } if(d[t]==INF) return false; flow+=a[t]; int u=t; while(u!=s){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; cost+=a[t]*edges[p[u]].cost; u=edges[p[u]].from; } return true; } int solve(){ int flow=0,cost=0; while(SPFA(flow,cost)); if (flow==k) return cost; else return -1; } }MM; int m,n,sum; int a[maxn]; int b[maxn]; int c[maxn][maxn]; void build(int k){ MM.init(m+n+2,0,m+n+1,sum); for (int i=1;i<=m;i++) MM.AddEdge(0,i,a[i],0); for (int j=1;j<=n;j++) MM.AddEdge(j+m,m+n+1,b[j],0); for (int i=1;i<=m;i++){ for (int j=1;j<=n;j++){ MM.AddEdge(i,j+m,INF,k*c[i][j]); } } } int main(){ read(m),read(n); for (int i=1;i<=m;i++) read(a[i]),sum+=a[i]; for (int i=1;i<=n;i++) read(b[i]); MM.init(m+n+2,0,m+n+1,sum); for (int i=1;i<=m;i++){ for (int j=1;j<=n;j++){ read(c[i][j]); } } build(1); printf("%d\n",MM.solve()); build(-1); printf("%d\n",MM.solve()*(-1)); return 0; }
- 1
信息
- ID
- 999
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者