POJ - 1470 题目
思路:tarjan
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int maxn = 1e3+10;
vector<int> h[maxn];
vector<int> query[maxn];
int f[maxn], anc[maxn], vis[maxn] , ans[maxn], isRoot[maxn];
int n,qnum;
void init()
{
for(int i = 1; i <= n; i++) {h[i].clear(); query[i].clear();}
for(int i = 1; i <= n; i++)
f[i] = i, vis[i] = 0, ans[i] = 0, isRoot[i] = 0;
}
int getf(int i)
{ return i == f[i] ? i : f[i] = getf(f[i]); }
void join(int i,int j)
{
int x = getf(i), y = getf(j);
if(x != y) f[y] = x;
}
void tarjan(int u)
{
//cout<<u<<endl;
anc[u] = u;
//cout<<h[u].size()<<endl;;
for(int i = 0; i < h[u].size(); i++)
{
int v = h[u][i];
tarjan(v);
join(u, v);
anc[getf(u)] = u;
}
vis[u] = 1;
for(int i = 0; i < query[u].size(); i++)
{
int v = query[u][i];
if(vis[v])
{
//cout<<anc[getf(v)] <<endl;
ans[anc[getf(v)]] ++;
}
}
}
int read()
{
char c;
int num = 0;
int a,b;
while(c = getchar())
{
if(c == '(')
{
scanf("%d%d",&a,&b);
query[a].push_back(b);
query[b].push_back(a);
num++;
}
if(num == qnum && c == ')') break;
}
return 0;
}
int main()
{
//freopen("D://in.txt","r",stdin);
while(~scanf("%d",&n))
{
int a,b,d,r = 0;
init();
for(int i = 0; i < n; i++)
{
scanf("%d",&a);
char c;
while(c = getchar())
{
if(c == '(') scanf("%d",&b);
if(c == ')') break;
}
for(int j = 0; j < b; j++)
{
scanf("%d",&d);
h[a].push_back(d);
isRoot[d]++;
}
}
for(int i = 1; i <= n; i++)
if(!isRoot[i]) r = i;
scanf("%d",&qnum);
read();
// fflush(stdin);
tarjan(r);
for(int i = 1; i <= n; i++)
if(ans[i]) printf("%d:%d\n",i,ans[i]);
}
return 0;
}