CodeForces - 1369E DeadLee(贪心+拓扑)

题目链接:点击查看

题目大意:Lee的厨房中有 n 道菜,每道菜的数量为 w[ i ] ,现在 Lee 会邀请 m 个朋友,每个朋友都有最爱吃的两道菜 x[ i ] 和 y[ i ] ,当朋友 i 来到 Lee 家后,会选择吃掉 x[ i ] 和 y[ i ] 各一份,如果 x[ i ] 没有了的话,那么他只会选择吃掉一份 y[ i ] ,如果 y[ i ] 没有了的话同理,但是如果 x[ i ] 和 y[ i ] 同时没有的话,这个朋友就会吃掉 Lee,问 Lee 能否安排一个合适的顺序以保证存活,输出这个顺序

题目分析:读完题后,需要发现的一个重要信息是,设 sum[ i ] 为每道菜的需求量,那么如果 sum[ i ] <= w[ i ] 的话,那么这 sum[ i ] 个人是一定可以吃到菜的,我们只需要将其安排在最后来吃就好了,同理,如果所有的 sum[ i ] > w[ i ] 成立的话,那么将会是无解的,因为假设 min_w 为所有 w[ i ] 中的最小值,那么至少会有 min_w 个人需要吃两个菜,换句话说我们无论安排谁最后来,都是需要吃两个菜的,这与我们的贪心策略不符

分析完后,实现的话用拓扑的思想就好了,只不过将拓扑中 du[ i ] == 0 的条件换成了 sum[ i ] <= w[ i ] 而已

代码:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=2e5+100;

int w[N],sum[N],n,m;

vector<pair<int,int>>node[N];

stack<int>ans;

bool vis[N];

bool topo()
{
	queue<int>q;
	for(int i=1;i<=n;i++)
		if(sum[i]<=w[i])
			q.push(i);
	while(q.size())
	{
		int u=q.front();
		q.pop();
		for(auto it:node[u])
		{
			int v=it.first,id=it.second;
			if(vis[id])
				continue;
			vis[id]=true;
			ans.push(id);
			if(--sum[v]<=w[v])
				q.push(v);
		}
	}
	return ans.size()==m;
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("input.txt","r",stdin);
//  freopen("output.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",w+i);
	for(int i=1;i<=m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		node[x].emplace_back(y,i);
		node[y].emplace_back(x,i);
		sum[x]++,sum[y]++;
	}
	if(topo())
	{
		puts("ALIVE");
		while(ans.size())
		{
			printf("%d ",ans.top());
			ans.pop();
		}
	}
	else
		puts("DEAD");












    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/106945138