POJ 2762
再贴一发Tarjan
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <stack>
#include <vector>
#include <queue>
using namespace std;
#define gmax(a,b) ((a) > (b) ? (a) : (b))
#define gmin(a,b) ((a) < (b) ? (a) : (b))
const int MAXN = 1000 + 5;
int n, m;
int pre[MAXN], low[MAXN], dfs_clock;
int sccno[MAXN], scc_cnt;
vector<int>lin[MAXN], lv[MAXN];
stack<int>sta;
queue<int>que;
int in[MAXN], vis[MAXN];
void dfs(int u)
{
pre[u] = low[u] = ++dfs_clock;
sta.push(u);
for(int i = 0 ; i < (int)lin[u].size() ; i++){
int v = lin[u][i];
if(pre[v] == 0){
dfs(v);
low[u] = gmin(low[u], low[v]);
}
else if(!sccno[v])
low[u] = gmin(low[u], pre[v]);
}
if(low[u] == pre[u]){
scc_cnt++;
while(!sta.empty()){
int org = sta.top(); sta.pop();
sccno[org] = scc_cnt;
if(org == u)
break;
}
}
}
bool check()
{
int ss = 0;
while(!que.empty()) que.pop();
for(int i = 1 ; i <= scc_cnt ; i++)
if(in[i] == 0) que.push(i);
if(que.size() > 1) return false;
while(!que.empty()){
int org = que.front(); que.pop();
vis[org] = 1;
for(int i = 0; i < (int)lv[org].size() ; i++){
int v = lv[org][i];
in[v]--;
}
for(int i = 1 ; i <= scc_cnt ; i++)
if(vis[i] == 0 && in[i] == 0) que.push(i);
if(que.size() > 1) return false;
ss++;
}
if(ss == scc_cnt)
return true;
return false;
}
void Tarjan()
{
while(!sta.empty()) sta.pop();
scc_cnt = 0;
memset(sccno, 0, sizeof(sccno));
memset(pre, 0, sizeof(pre));
dfs_clock = 0;
for(int i = 1 ; i <= n ; i++)
if(pre[i] == 0) dfs(i);
}
int main()
{
int t;
scanf("%d", &t);
while(t--){
scanf("%d%d", &n, &m);
for(int i = 1 ; i <= n ; i++)
lin[i].clear();
int u, v;
for(int i = 1 ; i <= m ; i++){
scanf("%d%d", &u, &v);
lin[u].push_back(v);
}
Tarjan();
memset(vis, 0, sizeof(vis));
memset(in, 0, sizeof(in));
for(int i = 1 ; i <= scc_cnt ; i++)
lv[i].clear();
for(int i = 1 ; i <= n ; i++){
for(int j = 0 ; j < (int)lin[i].size() ; j++){
int u = i, v = lin[i][j];
if(sccno[u] != sccno[v]){
lv[sccno[u]].push_back(sccno[v]);
in[sccno[v]]++;
}
}
}
if(check())
printf("Yes\n");
else
printf("No\n");
}
return 0;
}