题目描述
为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。
输入
输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。
输出
对于输入的每组数据,如果任意两个房间都是相互连接的,输出”Yes”,否则输出”No”。
样例
Sample Input
3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0
Sample Output
Yes
No
题意
判定的SCC个数,, mdzz 时间长不写代码 忘记了森林的情况
AC代码
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
#define ls st<<1
#define rs st<<1|1
#define fst first
#define snd second
#define MP make_pair
#define PB push_back
#define LL long long
#define PII pair<int,int>
#define VI vector<int>
#define CLR(a,b) memset(a, (b), sizeof(a))
#define ALL(x) x.begin(),x.end()
#define rep(i,s,e) for(int i=(s); i<=(e); i++)
#define tep(i,s,e) for(int i=(s); i>=(e); i--)
const int INF = 0x3f3f3f3f;
const int MAXN = 2e5+10;
const int mod = 1e9+7;
const double eps = 1e-8;
void fe() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt","w",stdout);
#endif
}
LL read()
{
LL x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
return x*f;
}
stack<int> S;
vector<int> E[MAXN];
int n, m;
int dfn[MAXN], low[MAXN], bl[MAXN], tot;
int cnt;
bool vis[MAXN];
void tarjan(int u) {
low[u] = dfn[u] = ++tot;
S.push(u);
vis[u] = true;
for(int i = 0; i < E[u].size(); i++) {
int v = E[u][i];
if(!dfn[v]) {
tarjan(v);
low[u] = min(low[v],low[u]);
}else if(vis[v]) {
low[u] = min(low[u],dfn[v]);
}
}
if(low[u] == dfn[u]) {
cnt++;
while(true) {
int v = S.top();
S.pop();
vis[v] = false;
if(v == u) break;
}
}
}
int main(int argc, char const *argv[])
{
while(cin >> n >> m, n||m) {
CLR(vis,false);
CLR(dfn,0);
CLR(low,0);
CLR(bl,0);
//for(int i = 0; i <= MAXN; i++) E[i].clear();
while(!S.empty()) S.pop();
tot = 0; cnt = 0;
for(int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
E[a].push_back(b);
}
for(int i = 1; i <= n; i++)
if(!dfn[i])
tarjan(i);
bool flag = true;
if(cnt > 1) {
flag = false;
}
if(flag)
cout << "Yes\n";
else
cout << "No\n";
for(int i = 0; i <= MAXN; i++) E[i].clear();
}
return 0;
}
/*
伪代码
tarjan(u) {
dfn[u] = low[u] = ++index; //为节点u设定编号
stack.push(u) // 节点u压入栈中
for each (u,v) in E
if(v is not visted) // 如果节点v未被访问过
tarjan(v) // 继续向下找
low[u] = min(low[u], low[v])
else if(v in S) // 如果节点u还在栈中
low[u] = min(low[u], dfn[v])
if (dfn[u] == low[u]) // 如果节点u是个强连通的根
repeat v = s.pop // 将v退栈,为该强连通分量中的一个顶点
print v
untile (u==v)
}
*/