poj 1330 Nearest Common Ancestors

深搜果然學的像屎一樣= =。

#pragma comment (linker, "/STACK:1024000000, 1024000000")
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAX = 10010;

bool flag;
int from,to,n;
bool root[MAX];
int tot,head[MAX];
int vis[MAX],dis[MAX],father[MAX];

struct edge{
	int v,next;
}node[MAX << 1];

void init(){
	tot = 0;
	flag = false;
	memset(root, true, sizeof(root));
	memset(head, -1, sizeof(head));
}

void addedge(int u, int v){
	node[tot].v = v;
	node[tot].next = head[u];
	head[u] = tot++; 
}

int find(int x){
	if(x != father[x])
		father[x] = find(father[x]);
	return father[x];
}

void lca(int u, int deep, int fa){
	vis[u] = fa;
	dis[u] = deep;
	father[u] = u;
	for(int i=head[u]; i!=-1; i=node[i].next){
		int v = node[i].v;
		if(vis[v] != -1) continue;
		lca(v, deep+1, fa);
		if(flag) return;
		father[v] = u;
	}
	if(u == from && vis[to] == fa){
		printf("%d\n",find(to));
		flag = true;
		return;
	}
	if(u == to && vis[from] == fa){
		printf("%d\n",find(from));
		flag = true;
		return;
	}
}

int main(){
	int cas;
	scanf("%d",&cas);
	while(cas--){
		scanf("%d",&n);
		init();
		for(int i=0; i<n-1; i++){
			int u, v;
			scanf("%d%d",&u,&v);
			root[v] = false;
			addedge(u, v);
			addedge(v, u);
		}
		scanf("%d%d",&from,&to);
		memset(vis, -1, sizeof(vis));
		int i;
		for(i=1; i<=n; i++)//= =。
			if(root[i]) break;
		lca(i, 0, i);
	}
	return 0;
}


發佈了240 篇原創文章 · 獲贊 5 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章