UVa10092: The Problem with the Problem Setter 题解

本文介绍了一种使用最大流算法解决特定问题的方法,包括构建超级源点和超级汇点,通过连边来表达题目间的限制条件,并利用最大流算法确定是否能够满足所有题型的要求题数总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立超级源点和超级汇点

超级源点向每道题目连一条流量为1的边

每种题型向超级汇点连一条流量为该题型的题目数的边,表示这种题型最多选这么多题

对于每道题的若干类型,在题目和类型之间连一条流量为1的边

跑最大流,判断maxflow是否等于sigma(所有题型要求的题数总和)

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#include <sstream>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;

const int MOD=1e9+7;
const int INF=0x7ffffff;
const int magic=348;

int t,tot,head[10048],nxt[200048],to[200048],f[200048];
inline void addedge(int s,int t,int cap)
{
	to[++tot]=t;nxt[tot]=head[s];head[s]=tot;f[tot]=cap;
	to[++tot]=s;nxt[tot]=head[t];head[t]=tot;f[tot]=0;
}

int k,p;
bool table[1048][48];

int depth[10048];queue<int> q;
bool bfs()
{
	int i,x,y;
	for (i=0;i<=t;i++) depth[i]=-1;
	depth[0]=0;q.push(0);
	while (!q.empty())
	{
		x=q.front();q.pop();
		for (i=head[x];i;i=nxt[i])
		{
			y=to[i];
			if (f[i] && depth[y]==-1)
			{
				depth[y]=depth[x]+1;
				q.push(y);
			}
		}
	}
	if (depth[t]==-1) return false; else return true;
}

int dfs(int x,int maxf)
{
	if (x==t) return maxf;
	int i,y,now,ans=0,minf;
	for (i=head[x];i;i=nxt[i])
	{
		y=to[i];
		if (f[i] && depth[y]==depth[x]+1)
		{
			minf=min(f[i],maxf-ans);
			now=dfs(y,minf);
			f[i]-=now;
			f[i^1]+=now;
			ans+=now;
			if (now==0) continue;
			if (1<=x && x<=p && p+1<=y && y<=p+k) table[x][y-p]=true;
			if (1<=y && y<=p && p+1<=x && x<=p+k) table[y][x-p]=false;
		}
	}
	return ans;
}

int main ()
{
	int i,j,u,x,num,sum;
	while (scanf("%d%d",&k,&p) && (k || p))
	{
		t=k+p+1;tot=1;for (i=0;i<=t;i++) head[i]=0;
		for (i=1;i<=p;i++)
			for (j=1;j<=k;j++)
				table[i][j]=false;
		for (i=1;i<=p;i++) addedge(0,i,1);
		sum=0;
		for (i=1;i<=k;i++)
		{
			scanf("%d",&x);
			sum+=x;
			addedge(p+i,t,x);
		}
		for (i=1;i<=p;i++)
		{
			scanf("%d",&num);
			while (num--)
			{
				scanf("%d",&x);
				addedge(i,p+x,1);
			}
		}
		int ans=0;
		while (bfs()) ans+=dfs(0,2e9);
		if (ans<sum)
		{
			printf("0\n");
			continue;
		}
		else
		{
			printf("1\n");
			for (i=1;i<=k;i++)
			{
				for (j=1;j<=p;j++)
					if (table[j][i]) printf("%d ",j);
				printf("\n");
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值