#include<stdio.h>
#define MAX (40000 + 1)
int numOfMilestones;
typedef struct{
int id;
int next;
}NODE;
NODE sonArray[MAX];//used as adjacent list
int sonNum;
int headArray[MAX];
int root;
typedef struct{
int nodeTime;
int maxDescendantTime;
}NODETIME;
NODETIME nodeTimeArray[MAX];
int time;
int numOfQuaries;
void DFS(int father){
time++;
nodeTimeArray[father].nodeTime = time;
nodeTimeArray[father].maxDescendantTime = time;
int indexOfSon;
for (indexOfSon = headArray[father]; indexOfSon != 0; indexOfSon = sonArray[indexOfSon].next){
int son = sonArray[indexOfSon].id;
DFS(son);
if (nodeTimeArray[son].maxDescendantTime > nodeTimeArray[father].maxDescendantTime){
nodeTimeArray[father].maxDescendantTime = nodeTimeArray[son].maxDescendantTime;
}
}
}
int main(){
scanf("%d", &numOfMilestones);
int indexOfMilestone;
for (indexOfMilestone = 1; indexOfMilestone <= numOfMilestones; indexOfMilestone++){
int son, father;
scanf("%d %d", &son, &father);
if (father == -1){
root= father;
}
sonNum++;
sonArray[sonNum].id = son;
sonArray[sonNum].next = headArray[father];
headArray[father] = sonNum;
}
DFS(root);
scanf("%d", &numOfQuaries);
int indexOfQuary;
for (indexOfQuary = 1; indexOfQuary <= numOfQuaries; indexOfQuary++){
int one, another;
scanf("%d %d", &one, &another);
if (nodeTimeArray[one].nodeTime < nodeTimeArray[another].nodeTime &&
nodeTimeArray[one].maxDescendantTime >= nodeTimeArray[another].nodeTime){
printf("1\n");
} else if (nodeTimeArray[another].nodeTime < nodeTimeArray[one].nodeTime &&
nodeTimeArray[another].maxDescendantTime >= nodeTimeArray[one].nodeTime){
printf("2\n");
} else {
printf("0\n");
}
}
return 0;
}
URAL 1329 Galactic History (DFS)
最新推荐文章于 2017-12-05 14:14:15 发布