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.
All data concerning customers planning to visit the farm on that particular day are available to Mirko early in the morning so that he can make a sales-plan in order to maximize the number of pigs sold.
More precisely, the procedure is as following: the customer arrives, opens all pig-houses to which he has the key, Mirko sells a certain number of pigs from all the unlocked pig-houses to him, and, if Mirko wants, he can redistribute the remaining pigs across the unlocked pig-houses.
An unlimited number of pigs can be placed in every pig-house.
Write a program that will find the maximum number of pigs that he can sell on that day.
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.
The next line contains M integeres, for each pig-house initial number of pigs. The number of pigs in each pig-house is greater or equal to 0 and less or equal to 1000.
The next N lines contains records about the customers in the following form ( record about the i-th customer is written in the (i+2)-th line):
A K1 K2 … KA B It means that this customer has key to the pig-houses marked with the numbers K1, K2, …, KA (sorted nondecreasingly ) and that he wants to buy B pigs. Numbers A and B can be equal to 0.
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
题目的大意是给定一个n,m。n是猪圈的数量,m是要去买猪的人数。
第二行表示1-n猪圈各个猪圈猪的数量。后面每行的第一个数表示每个人持有的钥匙数量。相应的钥匙打开相应的门,每行的最后一个数为想买猪的数量。当买家把猪圈门打开后,猪圈里面的猪可以移动到别的猪圈,但是必须是打开的猪圈。人走后猪圈门关闭。求卖家能卖猪的最大数量。
这一题最难的就是建图,建好图之后直接EK就好了。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
int map[999][999];
int p[6588];
int v[6588];
void EK(int n)//EK算法
{
int ans=0,flag;
while(1)
{
memset(p,0,sizeof(p));
memset(v,0,sizeof(v));
queue<int> q;
flag=0;
q.push(0);
v[0]=inf;
while(!q.empty())
{
int f=q.front();
q.pop();
for(int i=1;i<=n;i++)
{
if(v[i]==0&&map[f][i]>0)
{
v[i]=min(v[f],map[f][i]);
p[i]=f;
q.push(i);
if(i==n)
{
flag=1;
break;
}
}
}
}
if(!flag)
break;
for(int i=n;i!=0;i=p[i])
{
map[p[i]][i]-=v[n];
map[i][p[i]]+=v[n];
}
ans+=v[n];
}
printf("%d\n",ans);
}
int main()
{
int m,n;
scanf("%d%d",&m,&n);
int pig[6555],q[5655];
memset(map,0,sizeof(map));
memset(q,0,sizeof(q));
for(int i=1;i<=m;i++)
scanf("%d",&pig[i]);
int s,k;
for(int i=1;i<=n;i++)
{
scanf("%d",&s);
while(s--)
{
scanf("%d",&k);
if(q[k]==0)//第i个顾客是第一个到达k猪圈
{
map[0][i]+=pig[k];
q[k]=i;
}
else//表示顾客i紧跟在顾客q[k]后面打开第k个猪圈
{
map[q[k]][i]=inf;
q[k]=i;
}
}
scanf("%d",&k);
map[i][n+1]=k;//每个顾客到汇点的边,权值为顾客买猪的数量
}
EK(n+1);
return 0;
}