20pts求调
查看原帖
20pts求调
481621
Zhang_Wenjie楼主2024/3/29 13:50
#include <bits/stdc++.h>
#define re register int 
using namespace std;
const int N = 1e5 + 10;
int n, m;
int a[N], in[N];
priority_queue<int, vector<int>, greater<int> > q;
vector<int> b[N], g[N], tp, ans;
bool vis[N];

inline bool check(int mid)
{
	while (!q.empty()) q.pop();
	tp.clear();
	
	for (re i = 1; i <= mid; i ++)
	{
		for (re j = 1; j < b[i].size(); j ++)
		{
			int x = b[i][j - 1], y = b[i][j];
			g[x].push_back(y);
			in[y] ++;
		}
	}
//	cout << mid << '\n';
	for (re i = 1; i <= n; i ++)
		if (!in[i]) q.push(i);
	while (!q.empty())
	{
		int x = q.top(); q.pop();
		tp.push_back(x);
		for (re i = 0; i < g[x].size(); i ++)
		{
			int y = g[x][i];
			if (-- in[y] == 0) q.push(y);
		}
	}
	return (tp.size() == n ? true : false);
}

inline void copy_ans()
{
	int pos1, pos2;
	for (re i = 0; i < tp.size(); i ++)
	{
		if (tp[i] == ans[i]) continue;
		if (tp[i] < ans[i]) pos1 = i;
		else pos2 = i; 
	}
	if (pos1 > pos2) return;
	for (re i = 0; i < tp.size(); i ++)
		ans.push_back(tp[i]);
	
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	
	cin >> n >> m;
	for (re i = 1; i <= m; i ++)
	{
		cin >> a[i];
		for (re j = 1, x; j <= a[i]; j ++) 
			cin >> x, b[i].push_back(x);
			
		ans.push_back(N);
	}
/*	for (re i = 1; i <= m; i ++)
	{
		for (re j = 0; j < b[i].size(); j ++)
			cout << b[i][j] << ' ';
		cout << '\n';
	}
*/				
	int l = 0, r = m + 1;
	while (l + 1 < r)
	{
		int mid = (l + r) >> 1;
		if (check(mid)) l = mid, copy_ans();
		else r = mid;
	}
//	cout << ans.size() << '\n';
	for (re i = 0; i < ans.size(); i ++)
	{
		if (ans[i] == N || vis[ans[i]]) continue;
		cout << ans[i] << ' ';
		vis[ans[i]] = true;
	}
	
	return 0;
}
2024/3/29 13:50
加载中...