http://codevs.cn/problem/1506/
这道题就是问每个点是否存在于一个环里面,所以用tarjan跑一遍,然后检查他所在的强联通分量里面是否存在多于一个的变量数目。若变量数目大于1,输出T,否则输出F
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n, m;
vector <int> G[1005], com[1005];
int dfn[1005], low[1005], key[1005];
int ind, com_num;
int in[1005];
stack <int> s;
void tarjan(int x) {
key[x] = 2;
dfn[x] = low[x] = ind++;
s.push(x);
for(int i = 0; i < G[x].size(); i++) {
int v = G[x][i];
if(dfn[v] == -1) {
tarjan(v);
dfn[x] = min(dfn[x], dfn[v]);
} else if(key[v] == 2) {
dfn[x] = min(dfn[x], low[v]);
}
}
if(dfn[x] == low[x]) {
while(1) {
int t = s.top();
s.pop();
in[t] = com_num;
com[com_num].push_back(t);
key[t] = 1;
if(t == x)
break;
}
com_num++;
}
}
int main() {
int a, b;
memset(dfn, -1, sizeof(dfn));
memset(low, -1, sizeof(low));
int n, m;
cin >> n >> m;
while(m--) {
scanf("%d%d", &a, &b);
G[a].push_back(b);
}
for(int i = 1; i <= n; i++)
if(dfn[i] == -1)
tarjan(i);
for(int i = 1; i <= n; i++) {
if(com[in[i]].size() > 1)
cout << "T" << endl;
else
cout << "F" << endl;
}
return 0;
}