#65-【Tarjan】上白泽慧音

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82120074

Description

在幻想乡,上白泽慧音是以知识渊博闻名的老师。春雪异变导致人间之里的很多道路都被大雪堵塞,使有的学生不能顺利地到达慧音所在的村庄。因此慧音决定换一个能够聚集最多人数的村庄作为新的教学地点。人间之里由N个村庄(编号为1..N)和M条道路组成,道路分为两种一种为单向通行的,一种为双向通行的,分别用1和2来标记。如果存在由村庄A到达村庄B的通路,那么我们认为可以从村庄A到达村庄B,记为(A,B)。当(A,B)和(B,A)同时满足时,我们认为A,B是绝对连通的,记为<A,B>。绝对连通区域是指一个村庄的集合,在这个集合中任意两个村庄X,Y都满足<X,Y>。现在你的任务是,找出最大的绝对连通区域,并将这个绝对连通区域的村庄按编号依次输出。若存在两个最大的,输出字典序最小的,比如当存在1,3,4和2,5,6这两个最大连通区域时,输出的是1,3,4。

Input

第1行:两个正整数N,M

第2..M+1行:每行三个正整数a,b,t, t = 1表示存在从村庄a到b的单向道路,t = 2表示村庄a,b之间存在双向通行的道路。保证每条道路只出现一次。

Output

第1行: 1个整数,表示最大的绝对连通区域包含的村庄个数。

第2行:若干个整数,依次输出最大的绝对连通区域所包含的村庄编号。

Sample Input

5 5
1 2 1
1 3 2
2 4 2
5 1 2
3 5 1

Sample Output

3
1 3 5

HINT

 

对于60%的数据:N <= 200且M <= 10,000

对于100%的数据:N <= 5,000且M <= 50,000

 

强连通分量......

#include <iostream>
#include <stack>
#include <queue>
#include <cstring>

#define SIZE 5001

using namespace std;

struct comp // 优先队列不 让用函数......只能用结构体qaq
{
	bool operator ()(int a, int b)
	{
		return a > b;
	}
};

priority_queue<int, vector<int>, comp> ans, tempqueue; // 头大
vector<int> graph[SIZE];
stack<int> s;
int _max, dfn[SIZE], low[SIZE], dfstime;
bool instack[SIZE];

void tarjan(int now) // 模板
{
	int i, temp, tot = 0;
	
	s.push(now);
	instack[now] = true;
	dfn[now] = low[now] = ++dfstime;
	for (i = 0; i < graph[now].size(); ++i)
	{
		temp = graph[now][i];
		if (dfn[temp] == -1)
		{
			tarjan(temp);
			low[now] = min(low[now], low[temp]);
		}
		else if (instack[temp])
		{
			low[now] = min(low[now], dfn[temp]);
		}
	}
	if (low[now] == dfn[now])
	{
		while (!tempqueue.empty())
		{
			tempqueue.pop();
		}
		do
		{
			temp = s.top();
			s.pop();
			instack[temp] = false;
			++tot;
			tempqueue.push(temp); // 优先队列自动排序
		} while (temp != now);
		if (tot > _max)
		{
			_max = tot;
			ans = tempqueue;
		}
	}
	
	return;
}

int main(int argc, char** argv)
{
	int n, m, i, from, to, t;
	
	scanf("%d%d", &n, &m);
	for (i = 1; i <= m; ++i)
	{
		scanf("%d%d%d", &from, &to, &t);
		graph[from].push_back(to);
		if (t == 2)
		{
			graph[to].push_back(from);
		}
	}
	
	memset(dfn, -1, sizeof (dfn));
	for (i = 1; i <= n; ++i)
	{
		if (dfn[i] == -1)
		{
			tarjan(i);
		}
	}
	
	printf("%d\n", _max);
	while (!ans.empty())
	{
		printf("%d ", ans.top()); // 自动排序就能升序输出了嘛
		ans.pop();
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/82120074