您的位置:首页 > 编程语言 > C语言/C++

树上战争_hdu_2545(并查集).cpp

2013-11-10 14:53 316 查看


树上战争

Time Limit: 10000/4000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 450    Accepted Submission(s): 236


Problem Description

给一棵树,如果树上的某个节点被某个人占据,则它的所有儿子都被占据,lxh和pfz初始时分别站在两个节点上,谁当前所在的点被另一个人占据,他就输了比赛,问谁能获胜

 

Input

输入包含多组数据

每组第一行包含两个数N,M(N,M<=100000),N表示树的节点数,M表示询问数,N=M=0表示输入结束。节点的编号为1到N。

接下来N-1行,每行2个整数A,B(1<=A,B<=N),表示编号为A的节点是编号为B的节点的父亲

接下来M行,每行有2个数,表示lxh和pfz的初始位置的编号X,Y(1<=X,Y<=N,X!=Y),lxh总是先移动

 

Output

对于每次询问,输出一行,输出获胜者的名字

 

Sample Input

 2 1
1 2
1 2
5 2
1 2
1 3
3 4
3 5
4 2
4 5
0 0

 

Sample Output

 lxh
pfz
lxh

提示:
本题输入、输出都很多,请使用scanf和printf代替cin、cout。

 

Source

UESTC 6th Programming Contest Online

 

Recommend

lcy   |   We have carefully selected several similar problems for you:  2546 2538 2540 2539 2537 

#include<stdio.h>
int a[100001];
int find(int x,int y){
int i=0,j=0;
while(a[x]!=x){
i++;
x=a[x];
}
while(a[y]!=y){
j++;
y=a[y];
}
if(i<=j)
return 1;
else
return 0;
}
int main(){
int n,m;
while(1){
scanf("%d%d",&n,&m);
if(!(n||m))
break;

for(int i=1;i<=n;i++){
a[i]=i;
}
for(int i=1;i<n;i++){
int x,y;
scanf("%d%d",&x,&y);
a[y]=x;
}
for(int i=1;i<=m;i++){
int x,y;
scanf("%d%d",&x,&y);
if(find(x,y)){
printf("lxh\n");
}
else
printf("pfz\n");
}
}
return 0;
}


import java.io.InputStreamReader;
import java.util.Scanner;

public class Main{//java超时,C可过
static int a[];
public static void main(String[] args) {
Scanner input=new Scanner(new InputStreamReader(System.in));
while(true){
int n=input.nextInt();
int m=input.nextInt();
if(n==0&&m==0)
break;
a=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=i;
for(int i=1;i<n;i++){
int x=input.nextInt();
int y=input.nextInt();
a[y]=x;
}
for(int i=1;i<=m;i++){
int x=input.nextInt();
int y=input.nextInt();
if(find(x,y)){
System.out.println("lxh");
}
else
System.out.println("pfz");
}
}
}

private static boolean find(int x, int y) {
int i=0,j=0;
while(a[x]!=x){
i++;
x=a[x];
}
while(a[y]!=y){
j++;
y=a[y];
}
if(i<=j)
return true;
else
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并查集