顯然能夠想到的是入度為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