7.试题库问题
题目描述 Description
假设一个试题库中有n道试题。每道试题都标明了所属类别。同一道题可能有多个类别属性。现要从题库中抽取m道题组成试卷。并要求试卷包含指定类型的试题。试设计一个满足要求的组卷算法。
输入描述 Input Description
第1行有2个正整数n和k(2<=k<=20, k<=n<=1000)k表示题库中试题类型总数,n表示题库中试题总数。第2行有k个正整数,第i个正整数表示要选出的类型i的题数。这k个数相加就是要选出的总题数m。接下来的n行给出了题库中每个试题的类型信息。每行的第1个正整数p表明该题可以属于p类,接着的p个数是该题所属的类型号。
输出描述 Output Description
将组卷方案输出,第i 行输出 “i:”后接类型i的题号。如果有多个满足要求的方案,只要输出1个方案。如果问题无解,则输出”No Solution!”
样例输入 Sample Input
3 15
3 3 4
2 1 2
1 3
1 3
1 3
1 3
3 1 2 3
2 2 3
2 1 3
1 2
1 2
2 1 2
2 1 3
2 1 2
1 1
3 1 2 3
样例输出 Sample Output
1: 1 6 8
2: 7 9 10
3: 2 3 4 5
分析: 裸题,不想分析了···
建图: s向每一道试题连一条容量为1的边,每一道试题向它所属的类别连一条容量为1的边,每个类别向t连一条容量为数量要求的边
若最大流==m,则有解,否则无解
Code:
#include <bits/stdc++.h>
using namespace std;
struct node {
int to;
int next;
int flow;
}e[100000];
int f[10000],d[10000];
int head[10000],cur[10000];
int n,k,m=0,s,t,tot=1;
bool sum[30][1010];
int read() {
int ans=0,flag=1;
char ch=getchar();
while( (ch>'9' || ch<'0') && ch!='-' ) ch=getchar();
if(ch=='-') flag=-1,ch=getchar();
while(ch>='0' && ch<='9') ans=ans*10+ch-'0',ch=getchar();
return ans*flag;
}
void addedge(int u,int v,int w) {
e[++tot].to=v;
e[tot].flow=w;
e[tot].next=head[u];
head[u]=tot;
e[++tot].to=u;
e[tot].flow=0;
e[tot].next=head[v];
head[v]=tot;
return ;
}
int dfs(int now,int flow) {
if(now==t)
return flow;
int use=0;
for(int i=cur[now];i;i=e[i].next) {
cur[now]=i;
if(d[e[i].to]+1==d[now] && e[i].flow>0) {
int temp=dfs(e[i].to,min(flow-use,e[i].flow));
use+=temp;
e[i].flow-=temp;
e[i^1].flow+=temp;
if(flow==use)
return use;
}
}
cur[now]=head[now];
if(!(--f[d[now]]))
d[s]=n+k+2;
++f[++d[now]];
return use;
}
int main(){
k=read(),n=read();
s=0,t=n+k+1;
for(int i=1;i<=k;i++) {
int w=read();
m+=w;
addedge(i+n,t,w);
}
for(int i=1;i<=n;i++) {
addedge(s,i,1);
int num=read();
for(int j=1;j<=num;j++) {
int w=read();
addedge(i,w+n,1);
}
}
int ans=0;
f[0]=n+k+2;
while(d[s]<n+k+2)
ans+=dfs(s,1<<30);
if(ans==m) {
for(int i=2;i<=tot;i+=2) {
if(e[i].to==s || e[i^1].to==s) continue;
if(e[i].to==t || e[i^1].to==t) continue;
if(e[i^1].flow!=0)
sum[e[i].to-n][e[i^1].to]=1;
}
for(int i=1;i<=k;i++) {
printf("%d:",i);
for(int j=1;j<=n;j++) {
if(sum[i][j])
printf(" %d",j);
}
printf("\n");
}
}
else
printf("No Solution!");
return 0;
}