Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

1A 贴代码

Posted by 962861784 at 2011-06-17 13:12:17 on Problem 1330
#include<iostream>
#include<vector>
using namespace std;
const int MAX=10001;
vector<int>tree[MAX];
vector<int>que[MAX];
int parent[MAX],anscestor[MAX],indegree[MAX];
int check[MAX];
int n;
void init()
{
	for(int i=1;i<=n;i++)
	{
		tree[i].clear();
		que[i].clear();
		parent[i]=i;
		anscestor[i]=0;
		indegree[i]=0;
		check[i]=0;
	}
}
int find(int u)
{
	if(u==parent[u])return(u);
	else parent[u]=find(parent[u]);
	return parent[u];//压缩路径
}
void Union(int x,int y)
{
	parent[y]=x;
}
void LCA(int u)
{
	int i;
	parent[u]=u;
	for(i=0;i<tree[u].size();i++)
	{
		LCA(tree[u][i]);
		Union(u,tree[u][i]);
		anscestor[find(u)]=u;
	}
	check[u]=1;
	for(i=0;i<que[u].size();i++)
	{
		if(check[que[u][i]]==1)
		{
			printf("%d\n",anscestor[find(que[u][i])]);
			break;
		}
	}
}
int main()
{
	int tc;
	//freopen("1.txt","r",stdin);
	scanf("%d",&tc);
	while(tc--)
	{
		scanf("%d",&n);
		init();
		int i,u,v;
		for(i=1;i<n;i++)
		{
			scanf("%d %d",&u,&v);
			tree[u].push_back(v);
			indegree[v]++;
		}
		scanf("%d %d",&u,&v);
		que[u].push_back(v);
		que[v].push_back(u);
		for(i=1;i<=n;i++)
		if(indegree[i]==0)
		{
			LCA(i);
			break;
		}
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator