求强连通分量,缩点求出出度为0的点,从小到大输出。
英语不好这题读起来真拗口。
#include <iostream> #include <cstdio> #include <algorithm> #include <string> #include <cmath> #include <cstring> #include <queue> #include <set> #include <vector> #include <stack> #include <map> #include <iomanip> #define PI acos(-1.0) #define Max 100005 #define inf 1<<28 #define LL(x) (x<<1) #define RR(x) (x<<1|1) #define FOR(i,s,t) for(int i=(s);i<=(t);++i) #define ll long long #define mem(a,b) memset(a,b,sizeof(a)) #define mp(a,b) make_pair(a,b) using namespace std; struct kdq { int e ,next ; }ed[Max] ; int head[Max] ; int num1 = 0 ; int dfn[Max] ,low[Max] , st[Max] ,vis[Max] , belong[Max] ; int in[Max] ,out[Max] ; int tp = 0 ,dp = 0 ; int num = 0 ; set<int>ans[5005] ; void add(int a,int b) { ed[num1].e = b ; ed[num1].next =head[a] ; head[a] = num1 ++ ; } void init(int n ) { mem(dfn,-1) ; mem(vis,0) ; mem(low,0) ; mem(st,0) ; mem(belong,0) ; mem(in,0) ; mem(out,0) ; mem(head,-1) ; num = 0 ; num1 = 0 ; tp = 0 ; dp = 0 ; for (int i = 0 ;i <= n ;i ++ )ans[i].clear() ; } void tarjan(int now) { vis[now] = 1 ; st[tp ++ ] = now ; dfn[now] = low[now] = dp ++ ; for (int i = head[now] ; i != -1 ;i = ed[i].next ) { int v = ed[i].e ; if(dfn[v] == -1) tarjan(v) , low[now] = min(low[now], low[v]) ; else if(vis[v]) low[now] = min(low[now], dfn[v]) ; } if(low[now] == dfn[now]) { int xx ; num ++ ; do { xx = st[-- tp] ; vis[xx] = 0 ; belong[xx] = num ; ans[num].insert(xx) ; } while(xx != now) ; } } int n , m ; void solve() { while(cin >> n ,n ) { init(n) ; cin >> m ; for (int i = 0 ; i < m ;i ++) { int a, b ; scanf("%d%d",&a,&b) ; add(a,b) ; } for (int i = 1 ;i <= n ;i ++ ) if(dfn[i] == -1)tarjan(i) ; for (int i = 1 ;i <= n ;i ++ ) { for (int j = head[i] ;j != -1 ;j = ed[j].next ) { int x = belong[i] ; int y = belong[ed[j].e] ; if(x != y) { out[x] = 1 ; in[y] = 1 ; } } } set<int>::iterator it ; for (int i = 1 ;i <= num ;i ++) { if(out[i] == 0)//出度为0 { for (it = ans[i].begin() ; it != ans[i].end() ;it ++ ) { belong[*it] = 0 ;//置为0,从小到大输出 } } } for (int i = 1 ;i <= n; i ++)if(!belong[i])cout <<i <<" "; cout <<endl; } } int main() { solve() ; return 0; }