wannafly14C(tarjan缩点)

显然能够想到的是入度为0的一定要加的。。然后就剩下环了。。

环处理很容易想到缩点。。然后缩完点后再找入度为0的点就可以了。。

当然缩的时候记录一下最小下标。。



/**
 *        ┏┓    ┏┓
 *        ┏┛┗━━━━━━━┛┗━━━┓
 *        ┃       ┃  
 *        ┃   ━    ┃
 *        ┃ >   < ┃
 *        ┃       ┃
 *        ┃... ⌒ ...  ┃
 *        ┃       ┃
 *        ┗━┓   ┏━┛
 *          ┃   ┃ Code is far away from bug with the animal protecting          
 *          ┃   ┃   神兽保佑,代码无bug
 *          ┃   ┃           
 *          ┃   ┃        
 *          ┃   ┃
 *          ┃   ┃           
 *          ┃   ┗━━━┓
 *          ┃       ┣┓
 *          ┃       ┏┛
 *          ┗┓┓┏━┳┓┏┛
 *           ┃┫┫ ┃┫┫
 *           ┗┻┛ ┗┻┛
 */ 
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define mem(a) memset(a,0,sizeof(a))
#define ll long long
#define eps 1e-12
#define succ(x) (1<<x)
#define lowbit(x) (x&(-x))
#define sqr(x) ((x)*(x))
#define mid (x+y>>1)
#define NM 100005
#define nm 200005
#define pi 3.1415926535897931
using namespace std;
const ll inf=100000000000000005;
ll read(){
    ll x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
    return f*x;
}


struct edge{int t;edge*next;}e[nm],*h[NM],*o=e;
void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;}
int n,m,_x,_y,b[NM],c[NM],d[NM],suc[NM],low[NM],cnt,ans,tot;
stack<int>s;

void dfs(int x){
	d[x]=low[x]=++tot;s.push(x);
	link(x)if(!d[j->t]){
		dfs(j->t);low[x]=min(low[x],low[j->t]);
	}else if(!suc[j->t])low[x]=min(low[x],low[j->t]);
	if(low[x]==d[x]){
		c[++cnt]=x;int t;
		do{
			t=s.top();s.pop();
			suc[t]=cnt;c[cnt]=min(c[cnt],t);
		}while(x!=t);
	}
}

int main(){
	n=read();m=read();
	inc(i,1,m){_x=read();_y=read();add(_x,_y);}
	inc(i,1,n)if(!d[i])dfs(i);
	inc(i,1,n)link(i)if(suc[i]!=suc[j->t])b[suc[j->t]]++;
	inc(i,1,cnt)if(!b[i])d[++ans]=c[i];
	printf("%d\n",ans);
	sort(d+1,d+1+ans);
	inc(i,1,ans-1)printf("%d ",d[i]);
	return 0*printf("%d\n",d[ans]);
}





链接:https://www.nowcoder.com/acm/contest/81/C
来源:牛客网

可达性

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

给出一个 0 ≤ N ≤ 10 5 点数、0 ≤ M ≤ 10 5 边数的有向图,
输出一个尽可能小的点集,使得从这些点出发能够到达任意一点,如果有多个这样的集合,输出这些集合升序排序后字典序最小的。

输入描述:

第一行为两个整数 1 ≤ n, m ≤ 105,
接下来 M 行,每行两个整数 1 ≤ u, v ≤ 105 表示从点 u 至点 v 有一条有向边。
数据保证没有重边、自环。

输出描述:

第一行输出一个整数 z,表示作为答案的点集的大小;
第二行输出 z 个整数,升序排序,表示作为答案的点集。
示例1

输入

7 10
4 5
5 1
2 5
6 5
7 2
4 2
1 2
5 3
3 5
3 6

输出

2
4 7

猜你喜欢

转载自blog.csdn.net/qkoqhh/article/details/80025303