PIGS Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 19068 Accepted: 8697
Description
Mirko works on a pig farm that consists of M locked pig-houses and Mirko can't unlock any pighouse because he doesn't have the keys. Customers come to the farm one after another. Each of them has keys to some pig-houses and wants to buy a certain number of pigs.Input
The first line of input contains two integers M and N, 1 <= M <= 1000, 1 <= N <= 100, number of pighouses and number of customers. Pig houses are numbered from 1 to M and customers are numbered from 1 to N.Output
The first and only line of the output should contain the number of sold pigs.Sample Input
3 3 3 1 10 2 1 2 2 2 1 3 3 1 2 6
Sample Output
7
Source
Croatia OI 2002 Final Exam - First day
最大流。
構圖方式:
①把每個顧客看作除源點和匯點以外的節點。
②從源點向每個豬圈的第一個顧客連一條邊,容量為該豬圈最初的豬的數量。
③每個豬圈的前後兩個顧客之間連一條邊,容量為正無窮。因為可以任意分配每個豬圈中的豬的數量。
④從每個顧客向匯點連一條邊,容量為要購買的豬的數量。
這道題的構圖方法很巧妙。
#include#include #include #include #include #include #include #define F(i,j,n) for(int i=j;i<=n;i++) #define D(i,j,n) for(int i=j;i>=n;i--) #define LL long long #define pa pair #define MAXN 105 #define MAXM 1005 #define INF 1000000000 using namespace std; int n,m,k,x,s,t,cnt=1,ans=0; int pre[MAXM],head[MAXN],cur[MAXN],dis[MAXN],c[MAXN],a[MAXM]; bool vst[MAXM],f[MAXN]; struct edge_type { int next,to,v; }e[10005]; inline int read() { int x=0,f=1;char ch=getchar(); while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } inline void add_edge(int x,int y,int v) { e[++cnt]=(edge_type){head[x],y,v};head[x]=cnt; e[++cnt]=(edge_type){head[y],x,0};head[y]=cnt; } inline bool bfs() { queue q; memset(dis,-1,sizeof(dis)); dis[s]=0;q.push(s); while (!q.empty()) { int tmp=q.front();q.pop(); if (tmp==t) return true; for(int i=head[tmp];i;i=e[i].next) if (e[i].v&&dis[e[i].to]==-1) { dis[e[i].to]=dis[tmp]+1; q.push(e[i].to); } } return false; } inline int dfs(int x,int f) { int tmp,sum=0; if (x==t) return f; for(int &i=cur[x];i;i=e[i].next) { int y=e[i].to; if (e[i].v&&dis[y]==dis[x]+1) { tmp=dfs(y,min(f-sum,e[i].v)); e[i].v-=tmp;e[i^1].v+=tmp;sum+=tmp; if (sum==f) return sum; } } if (!sum) dis[x]=-1; return sum; } inline void dinic() { while (bfs()) { F(i,1,n+2) cur[i]=head[i]; ans+=dfs(s,INF); } } int main() { memset(head,0,sizeof(head)); memset(c,0,sizeof(c)); memset(vst,false,sizeof(vst)); m=read();n=read();s=n+1;t=n+2; F(i,1,m) a[i]=read(); F(i,1,n) { memset(f,false,sizeof(f)); k=read(); while (k--) { x=read(); if (!vst[x]) {vst[x]=true;c[i]+=a[x];} if (pre[x]&&!f[pre[x]]) add_edge(pre[x],i,INF),f[pre[x]]=true; pre[x]=i; } x=read();if (x) add_edge(i,t,x); } F(i,1,n) if (c[i]) add_edge(s,i,c[i]); dinic(); printf("%d\n",ans); }