题目链接:https://cn.vjudge.net/problem/POJ-1904
题解链接:http://www.cnblogs.com/zxndgv/archive/2011/08/06/2129333.html
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 4005;
const int M = 400005;
const int INF = 0x3f3f3f3f;
struct edge {
int to, next;
}graph[M];
int totlen;
int head[N];
int n, m, k;
void init() {
totlen = 0;
memset(head, -1, sizeof head);
}
void addEdge(int u, int v) {
graph[totlen] = {v, head[u]};
head[u] = totlen++;
}
int scc_cnt, dfs_rank;
int low[N];
int dfn[N];
int belong[N];
bool instack[N];
stack<int> sta;
void tarjan(int u) {
sta.push(u);
instack[u] = true;
low[u] = dfn[u] = ++dfs_rank;
for(int i = head[u]; i != -1; i = graph[i].next) {
int v = graph[i].to;
if(!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
}else if(instack[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if(low[u] == dfn[u]) {
scc_cnt++;
int v;
do {
v = sta.top(); sta.pop();
instack[v] = false;
belong[v] = scc_cnt;
} while(v != u);
}
}
void SCC() {
scc_cnt = dfs_rank = 0;
memset(dfn, 0, sizeof dfn);
for(int i = 1; i <= n; i++)
if(!dfn[i])
tarjan(i);
}
int main() {
init();
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &m);
for(int j = 0; j < m; j++) {
scanf("%d", &k);
addEdge(i, n+k);
}
}
for(int i = 1; i <= n; i++) {
scanf("%d", &k);
addEdge(n+k, i);
}
SCC();
vector<int> ans;
for(int i = 1; i <= n; i++) {
ans.clear();
for(int j = head[i]; j != -1; j = graph[j].next) {
if(belong[graph[j].to] == belong[i]) {
ans.push_back(graph[j].to-n);
}
}
sort(ans.begin(), ans.end());
int tot = ans.size();
printf("%d", tot);
for(int i = 0; i < tot; i++) {
printf(" %d", ans[i]);
}
printf("\n");
}
return 0;
}