您的位置:首页 > 其它

poj 3237 Tree(最近公共祖先)

2013-08-07 16:39 351 查看
Tree

Time Limit: 5000MSMemory Limit: 131072K
Total Submissions: 2802Accepted: 762
Description

You are given a tree with N nodes. The tree’s nodes are numbered 1 through N and its edges are numbered 1 through N − 1. Each edge is associated with a weight. Then you are to execute a series of instructions on the tree. The instructions
can be one of the following forms:

CHANGE
i v
Change the weight of the ith edge to v
NEGATE
a b
Negate the weight of every edge on the path from a to b
QUERY
a b
Find the maximum weight of edges on the path from a to b
Input

The input contains multiple test cases. The first line of input contains an integer t (t ≤ 20), the number of test cases. Then follow the test cases.

Each test case is preceded by an empty line. The first nonempty line of its contains N (N ≤ 10,000). The next N − 1 lines each contains three integers a, b and c, describing an edge connecting nodes a and b with
weight c. The edges are numbered in the order they appear in the input. Below them are the instructions, each sticking to the specification above. A lines with the word “
DONE
” ends the test case.

Output

For each “
QUERY
” instruction, output the result on a separate line.

Sample Input
1

3
1 2 1
2 3 2
QUERY 1 2
CHANGE 1 3
QUERY 1 2
DONE


Sample Output
1
3


Source

POJ Monthly--2007.06.03, Lei, Tao

题意:对一棵树做3个操作

题解:爬坡算法...求最近公共祖先.. 水过...罪过...

#include<stdio.h>
#include<string.h>
int head[10005],fath[10005];
int wei[10005],deep[10005];
int id[10005],vis[10005],all;
struct edge
{
int data,next,len,id;
} p[20005];
int MAX(int a,int b){ return a>b?a:b; }
void add(int x,int y,int len,int id)
{
p[all].next=head[x];
p[all].data=y;
p[all].len=len;
p[all].id=id;
head[x]=all++;
}
void dfs(int x,int d)
{
int i;

deep[x]=d;  vis[x]=1;
for(i=head[x]; i!=-1; i=p[i].next)
{
if(vis[p[i].data]) continue;
wei[p[i].data]=p[i].len;
fath[p[i].data]=x;
id[p[i].id]=p[i].data;
dfs(p[i].data,d+1);
}
}
void Q(int x,int y)
{
int res=-0xffffff;

if(deep[x]<deep[y])
{
x=x+y;
y=x-y;
x=x-y;
}
while(deep[x]>deep[y])
{
res=MAX(wei[x],res);
x=fath[x];
}
while(x!=y)
{
res=MAX(MAX(res,wei[x]),wei[y]);
x=fath[x],y=fath[y];
}
printf("%d\n",res);
}
void N(int x,int y)
{
if(deep[x]<deep[y])
{
x=x+y;
y=x-y;
x=x-y;
}
while(deep[x]>deep[y])
{
wei[x]=-wei[x];
x=fath[x];
}
while(x!=y)
{
wei[x]=-wei[x],wei[y]=-wei[y];
x=fath[x],y=fath[y];
}
}
int main()
{
int t,n,i,x,y,z;
char s[10];

//freopen("t.txt","r",stdin);
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(head,-1,sizeof(head));
for(all=i=0; i<n-1; i++)
{
scanf("%d%d%d",&x,&y,&z);
add(x,y,z,i+1),add(y,x,z,i+1);
}
memset(vis,0,sizeof(vis));
dfs(1,0);
while(scanf("%s",s),s[0]!='D')
{
scanf("%d%d",&x,&y);
if(s[0]=='C') wei[id[x]]=y;
else if(s[0]=='Q') Q(x,y);
else N(x,y);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: