题意很简单。。
Sample Input
5 5:(3) 1 4 2 1:(0) 4:(0) 2:(1) 3 3:(0) 6 (1 5) (1 4) (4 2) (2 3) (1 3) (4 3)
Sample Output
2:1 5:5输入一个数n,表示节点数,然后接下来是每个节点的边。
再输入m,表示有多少个询问。
输入比较恶心。处理一下然后发现时间消耗很大。这题1900MS A掉的;
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <stack>
#include <map>
#include <iomanip>
#define PI acos(-1.0)
#define Max 2005
#define inf 1<<28
using namespace std;
vector<int>g[Max],q[Max];
int f[Max],LCA[Max];
bool visit[Max];
int ans[Max];
bool notfather[Max];
int n;
bool flag=0;
int find(int x)
{
if(f[x]==x)
return x;
return f[x]=find(f[x]);
}
void tarjan(int u)
{
int i,j;
for(i=0; i<g[u].size(); i++)
{
tarjan(g[u][i]);
f[g[u][i]]=u;
}
visit[u]=1;
for(i=0; i<q[u].size(); i++)//询问
{
if(visit[q[u][i]])
{
ans[find(q[u][i])]++;//找到答案++
}
}
}
void init()
{
int i,j;
for(i=0; i<=n; i++)
{
visit[i]=0;
ans[i]=0;
f[i]=i;
g[i].clear();
q[i].clear();
notfather[i]=0;
}
}
int main()
{
int i,j,k,l,m,T,fa;
char L,R,K;
int a,b;
while(scanf("%d",&n)!=EOF)
{
init();
for(i=0; i<n; i++)
{
scanf("%d:(%d)",&a,&m);
while(m--)
{
scanf("%d",&b);
g[a].push_back(b);
notfather[b]=1;
}
}
for(i=1; i<=n; i++)
{
if(!notfather[i])
{
fa=i;
break;
}
}
scanf("%d",&m);
while(m--)
{
cin>>L>>a>>b>>R;
q[a].push_back(b);
q[b].push_back(a);
}
tarjan(fa);
for(i=1; i<=n; i++)
{
if(ans[i])
printf("%d:%d\n",i,ans[i]);
}
}
return 0;
}
LCA的模版题。就是输入处理有点麻烦。