跳到正文

题解

P5603 小 C 与桌游 题解

LaplaceDuck约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月12日
收录
2026年8月20日
更新
2026年8月20日
篇幅
约 3 分钟
题目
P5603

版本

  1. v1当前

P5603 小 C 与桌游 题解

思路

第一问就不说了,主要说第二问。经过思考,发现可以分层来做,找每一层的最大值,看它是不比之前的最大值大,如果大则就更新。

如图,先把第一层的最大值求出,再处理第二层。

可是,若是这样一个图则会发生一定的问题。

若按刚刚的思路,会先把第二层处理掉,再去处理第三层,接着第四层。但是事实上,可以直接去取 1414,这样是最优的。所以要改进。如果当前队中的点,有小于上一轮的最大值的,把这个点的后继也入队,直到队中的所有点都大于上轮最大值,更新答案和最大值。

代码

C++
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 5e5 + 5;

int m, n, in1[MAXN], in2[MAXN]; vector <int> G[MAXN]; priority_queue <int, vector <int>, greater <int> > pq1, pq2;

int main()
{
	cin >> n >> m;
	
	for (int i = 1; i <= m; i ++)
	{
		int u, v; cin >> u >> v; G[u].push_back(v); in1[v] ++; in2[v] ++;
	}
	
	for (int i = 1; i <= n; i ++) if (!in1[i]) pq1.push(i);
	
	int cnt = 0, maxx = 0;
	
	while (!pq1.empty())
	{
		int u = pq1.top(); pq1.pop();
		
		if (u > maxx)
		{
			maxx = u; cnt ++;
		}
		
		for (int v : G[u])
		{
			in1[v] --; if (!in1[v]) pq1.push(v);
		}
	}
	
	cout << cnt << "\n";
	
	cnt = maxx = 0;
	
	for (int i = 1; i <= n; i ++) if (!in2[i]) pq2.push(i);
	
	while (!pq2.empty())
	{
		int u = pq2.top();
		
		if (u < maxx)
		{
			pq2.pop();
			
			for (int v : G[u])
			{
				in2[v] --; if (!in2[v]) pq2.push(v);
			}
		}
		
		if (u > maxx)
		{
			cnt ++; vector <int> tmp;
			
			while (!pq2.empty())
			{
				int x = pq2.top(); pq2.pop();
				
				for (int v : G[x])
				{
					in2[v] --; if (!in2[v]) tmp.push_back(v);
				}
				
				maxx = x;
			}
			
			for (int i : tmp) pq2.push(i);
		}
	}
	
	cout << cnt;
	
	return 0;
}
原文