求助 只过了一个样例 wqw
查看原帖
求助 只过了一个样例 wqw
601916
Haii楼主2022/8/4 14:50
#include <bits/stdc++.h>

using namespace std;

int const N = 100010;
int const M = 2000010;
int h[N], ne[M], e[M], idx, st[N];

typedef pair<int, int> PII;
PII a[N];
int n, m;

void add(int a, int b)
{
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}

bool cmp(const PII& a1, const PII& a2)
{
	if (a1.first != a2.first) return a1.first < a2.first;
	if (a1.second != a2.second) return a1.second > a2.second;
	return false;
}

void dfs(int u, int cnt)
{
	st[u] = true;
	cout << u << ' ';
	if (cnt == n) return;
	for (int i = h[u]; i != -1; i = ne[i])
	{
		int j = e[i];
		if (!st[j]) dfs(j, cnt + 1);
	}
}

void bfs()
{
	queue<int> q;
	q.push(1);
	st[1] = true;
	while (!q.empty())
	{
		int t = q.front();
		q.pop();
		cout << t << ' ';
		for (int i = h[t]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (!st[j])
			{
				st[j] = true;
				q.push(j);

			}
		}
	}
}

int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0; i < m; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + m, cmp);
	for (int i = 0; i < m; i++)
		add(a[i].first, a[i].second);
	dfs(1, 0);
	puts("");
	memset(st, 0, sizeof st);
	bfs();

	return 0;
}
2022/8/4 14:50
加载中...