AC on #6,其他WA求助
查看原帖
AC on #6,其他WA求助
364848
Bodhi楼主2022/11/24 11:27

应该不是tarjan的问题啊。。 我用的是map存储答案

测评记录

#include <bits/stdc++.h>
using namespace std;

const int M = 1e5 + 10, N = 1e4 + 10;
using tr = map<int, int>::iterator;
// struct Edge
// {
// 	int to, next;
// } e[M];
// int cnt, head[M];
// void add(int x, int y)
// {
// 	++cnt;
// 	e[cnt] = {y, head[x]};
// 	head[x] = cnt;
// }

int dfn[N], low[N], times, tot;
map<int, int> mm;
vector<int> v[N], ans[N];
stack<int> s;
bool b[N];
void tarjan(int x)
{
	dfn[x] = low[x] = ++times;
	s.push(x);
	b[x] = true;
	int to;
	for (int j = 0; j < v[x].size(); ++j)
	{
		to = v[x][j];
		// to = e[j].to;
		if (!dfn[to])
		{
			tarjan(to);
			low[x] = min(low[x], low[to]);
		}
		else if (b[to])
			low[x] = min(low[x], dfn[to]);
	}
	if (dfn[x] == low[x])
	{
		++tot;
		mm[x] = tot;
		while (x != s.top())
		{
			ans[tot].push_back(s.top());
			b[s.top()] = false;
			s.pop();
		}
		ans[tot].push_back(s.top());
		b[s.top()] = false;
		s.pop();
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n, m, i, j, x, y;
	cin >> n >> m;
	for (j = 1; j <= m; ++j)
	{
		cin >> x >> y;
		if (x == y)
			continue;
		v[x].push_back(y);
		// add(x, y);
	}
	for (j = 1; j <= n; ++j)
	{
		if (dfn[j] == 0)
		{
			tarjan(j);
		}
	}
	// for (i = 1; i <= n; ++i)
	// {
	// 	cout << i << "dfn:" << dfn[i] << "low:" << low[i] << '\n';
	// }
	for (tr i = mm.begin(); i != mm.end(); ++i)
	{
		sort(ans[i->second].begin(), ans[i->second].end());
	}
	cout << tot << '\n';
	for (tr i = mm.begin(); i != mm.end(); ++i)
	{
		for (j = 0; j < ans[i->second].size(); ++j)
		{
			cout << ans[i->second][j] << ' ';
		}
		cout << '\n';
	}
	return 0;
}

2022/11/24 11:27
加载中...