链接:
https://www.nowcoder.com/acm/contest/81/C
来源:牛客网
来源:牛客网
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<stack>
#define ll long long
using namespace std;
void dis(int a[], int n){
printf("总数为%d个\n",n);
for(int i = 1; i <= n; i++) cout<<a[i]<<", ";
cout<<endl<<"------------------"<<endl;
}
const int mx = 1e5+10;
int n,m;
vector<int>ma[mx],ans;
stack<int>st;
int dfn[mx],low[mx],belong[mx],res[mx],add,id;
bool vis[mx];
int in[mx];
void tarjan(int u){
int v,te;
st.push(u);
vis[u] = 1;
dfn[u] = low[u] = ++add;
for(int i = 0; i < ma[u].size(); i++){
v = ma[u][i];
if(!dfn[v]){
tarjan(v);
low[u] = min(low[u],low[v]);
}
else if(vis[v]){
low[u] = min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u]){
id++;
while(1){
te = st.top();
st.pop();
vis[te] = 0;
belong[te] = id;
if(te == u)
break;
}
}
}
int main(){
int u,v;
scanf("%d%d",&n,&m);
while(m--){
scanf("%d%d",&u,&v);
ma[u].push_back(v);
}
memset(dfn,0,sizeof(dfn));
memset(vis,0,sizeof(vis));
memset(in,0,sizeof(in));
add = id = 0;
for(int i = 1; i <= n; i++){
if(!dfn[i])
tarjan(i);
}
for(int i = 1; i <= n; i++){
for(int j = 0; j < ma[i].size(); j++){
v = ma[i][j];
if(belong[i] != belong[v]) //belong【v】错写成 v
in[belong[v]]++;
}
}
//dis(in,n);
memset(res,0x3f3f3f,sizeof(res));
for(int i = 1; i <= n; i++)
res[belong[i]] = min(res[belong[i]],i);
for(int i = 1; i <= id; i++){ //错写id
if(!in[i])
ans.push_back(res[i]);
}
sort(ans.begin(),ans.end());
cout<<ans.size()<<endl;
for(int i = 0; i < ans.size(); i++){
if(i == 0)
printf("%d",ans[i]);
else
printf(" %d",ans[i]);
}
cout<<endl;
// dis(belong,n);
return 0;
}