洛谷 P1726 上白泽慧音
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
Data Size
对于60%的数据:N <= 200且M <= 10,000
对于100%的数据:N <= 5,000且M <= 50,000
题解:
- tarjan。
- 找最大强连通分量就OK了。稍微注意处理一下答案一样按字典序排序的问题。
#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <cstring>
#define N 5005
#define M 100005
using namespace std;
struct E {int next, to;} e[M];
int n, m, num, dex, ans;
int h[N], dfn[N], low[N], seq[N], t[N];
bool vis[N];
stack<int> stk;
int read()
{
int x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x;
}
void add(int u, int v)
{
e[++num].next = h[u];
e[num].to = v;
h[u] = num;
}
bool check(int a[], int b[])
{
for(int i = 1; i <= ans; i++)
if(a[i] < b[i]) return 1;
else if(a[i] > b[i]) return 0;
return 0;
}
void tarjan(int x)
{
dfn[x] = low[x] = ++dex;
stk.push(x), vis[x] = 1;
for(int i = h[x]; i != 0; i = e[i].next)
{
if(!dfn[e[i].to])
tarjan(e[i].to),
low[x] = min(low[x], low[e[i].to]);
else if(vis[e[i].to])
low[x] = min(low[x], dfn[e[i].to]);
}
if(dfn[x] == low[x])
{
int tot = 0;
while(1)
{
int now = stk.top();
stk.pop(), vis[now] = 0;
t[++tot] = now;
if(now == x) break;
}
sort(t + 1, t + 1 + tot);
if(tot > ans)
{
for(int i = 1; i <= tot; i++) seq[i] = t[i];
ans = tot;
}
else if(tot == ans && check(t, seq))
for(int i = 1; i <= tot; i++) seq[i] = t[i];
}
}
int main()
{
memset(seq, 0x3f, sizeof(seq));
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int u = read(), v = read(), op = read();
add(u, v);
if(op == 2) add(v, u);
}
for(int i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
sort(seq + 1, seq + 1 + ans);
cout << ans << endl;
for(int i = 1; i <= ans; i++) printf("%d ", seq[i]);
return 0;
}