1332 上白泽慧音

1332 上白泽慧音

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
 
 
 
题目描述 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 Description

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

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

输出描述 Output Description

第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 & Hint

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

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

分类标签 Tags 点此展开 

 
 
AC代码:
#include<cstdio>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
const int N=1e5+10;
struct node{
    int w;
    vector<int>p;
    void px(){sort(p.begin(),p.end());}
    bool operator < (const node &a) const{
        if(w==a.w){
            for(int i=0;i<w;i++){
                if(p[i]==a.p[i]) continue;
                return p[i]<a.p[i];
            }
        }
        return w>a.w;
    }
}ans[N];
int pd,sd,dfn[N],low[N];
bool mark[N];
vector<int>grap[N];
stack<int>s;
inline const int read(int &x){
    register char ch=getchar();x=0;
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
}
void tarjan(int v){
    dfn[v]=low[v]=++pd;
    mark[v]=1;
    s.push(v);
    for(int i=0;i<grap[v].size();i++){
        int w=grap[v][i];
        if(!dfn[w]){
            tarjan(w);
            low[v]=min(low[v],low[w]);
        }
        else if(mark[w]){
            low[v]=min(low[v],dfn[w]);
        }
    }
    int u;
    if(dfn[v]==low[v]){
        sd++;
        do{
            u=s.top();
            s.pop();
            ans[sd].w++;
            ans[sd].p.push_back(u); 
            mark[u]=0;
        }while(u!=v);
    }
}
int main(){
    int n,m,x,y,z;
    read(n);read(m);
    for(int i=1;i<=m;i++){
        read(x);read(y);read(z);
        if(x==y) continue;
        if(z==1) grap[x].push_back(y); 
        else grap[x].push_back(y),grap[y].push_back(x); 
    }
    for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);
    sort(ans+1,ans+sd+1);
    ans[1].px();
    printf("%d
",ans[1].w);
    for(int i=0;i<ans[1].w;i++) printf("%d ",ans[1].p[i]);
    return 0;
}
原文地址:https://www.cnblogs.com/shenben/p/5879305.html