有点暴力的图论…
方法:
枚举每一个节点
进行正反边搜索
正反边的遍历节点总数为N即为解
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 1005;
vector<int> a[MAXN];
vector<int> ra[MAXN];
int n,m;
bool bfs(int cur)
{
int sum = 0;
queue<int> que;
que.push(cur);
int book[MAXN] = {0};
book[cur] = 1;
while(!que.empty())
{
int t = que.front();
que.pop();
sum++;
for(int i=0;i < a[t].size();i++)
{
if(!book[a[t][i]])
que.push(a[t][i]),book[a[t][i]] = 1;
}
}
if(sum == n)
return true;
sum = 0;
que.push(cur);
int bk[MAXN] = {0};
bk[cur] = 1;
while(!que.empty())
{
int t = que.front();
que.pop();
// sum++;
for(int i=0;i<ra[t].size();i++)
{
if(!bk[ra[t][i]])
que.push(ra[t][i]),bk[ra[t][i]] = 1;
}
}
for(int i=1;i<=n;i++)
if(book[i] || bk[i])
sum++;
if(sum == n)
return true;
return false;
}
int main()
{
scanf("%d %d",&n,&m);
while(m--)
{
int x,y;
scanf("%d %d",&x,&y);
a[x].push_back(y);
ra[y].push_back(x);
}
int ans= 0 ;
for(int i=1;i<=n;i++)
{
if(bfs(i))
ans++;
}
cout<<ans;
return 0;
}