poj 1330
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<string.h>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = (int)1e4+5;
int r[maxn];
int f[maxn];
int ansc[maxn];
int dgr[maxn];
bool visit[maxn];
vector<int> c[maxn];
vector<int> q[maxn];
int findf(int x){
if(x != f[x]){
f[x] = findf(f[x]);
}
return f[x];
}
int unify(int x,int y){
int fx = findf(x);
int fy = findf(y);
if(fx == fy){
return 0;
}
if(r[fx] < r[fy]){
f[fx] = fy;
r[fy] += r[fx];
}
else{
f[fy] = fx;
r[fx] += r[fy];
}
return 1;
}
int n;
void init(){
for(int i = 0; i < n; ++i){
r[i] = 1;
f[i] = i;
dgr[i] = 0;
visit[i] = false;
c[i].clear();
q[i].clear();
ansc[i] = 0;
}
}
int LCA(int x){
ansc[x] = x;
int size = c[x].size();
for(int i = 0; i < size; ++i){
LCA(c[x][i]);
unify(x,c[x][i]);
ansc[findf(x)] = x;
}
visit[x] = true;
size = q[x].size();
for(int i = 0; i < size; ++i){
if(visit[q[x][i]]){
printf("%d
",ansc[findf(q[x][i])] + 1);
return 0;
}
}
return 0;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
init();
int a, b;
for(int i = 0; i < n - 1; ++i){
scanf("%d%d",&a,&b);
--a;
--b;
c[a].push_back(b);
dgr[b]++;
}
scanf("%d%d",&a,&b);
--a; --b;
q[a].push_back(b);
q[b].push_back(a);
for(int i = 0; i < n; ++i){
if(dgr[i] == 0){
LCA(i);
break;
}
}
}
return 0;
}
Tarjan은 트리에서 lca 문제를 해결하는 오프라인 알고리즘입니다.
깊이를 바탕으로 우선적으로 주유하고 모으다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.