spoj 375 Query on a tree(树链剖分,边,线段树)

来源:互联网 发布:手机用数据会出400bad 编辑:程序博客网 时间:2024/05/02 05:06

题目:http://vjudge.net/contest/28982#problem/I
题意:

给一棵树,进行两种操作:
1.把第i条边权值改为x
2.查询a到b路径上的最大边权

分析:

树链剖分入门题,基于边的重编号
操作:单点更新+区间查询最值
用线段树维护操作

一篇很好的树链剖分的入门文章:http://blog.sina.com.cn/s/blog_6974c8b20100zc61.html
代码:

#include <cstdio>#include <algorithm>#include <iostream>#include <string.h>using namespace std;#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1const int N = 10010;struct EDGE {    int v,nex;} edge[N<<1];int head[N],tot;int dep[N],p[N],fa[N],top[N],son[N],siz[N];int cnt,maxn[N<<2];void addedge(int a,int b,int c) {    edge[tot].v=b;    edge[tot].nex=head[a];    head[a]=tot++;}void dfs(int u) {    siz[u]=1,son[u]=0;    for(int i=head[u]; ~i; i=edge[i].nex) {        int v=edge[i].v;        if(v!=fa[u]) {            fa[v]=u;            dep[v]=dep[u]+1;            dfs(v);            if(siz[v]>siz[son[u]])son[u]=v;            siz[u]+=siz[v];        }    }}void build(int u,int tp) {    p[u]=++cnt;    top[u]=tp;    if(son[u])build(son[u],tp);    for(int i=head[u]; ~i; i=edge[i].nex) {        int v=edge[i].v;        if(v!=son[u]&&v!=fa[u])build(v,v);    }}void update(int p,int x,int l,int r,int rt) {    if(l==r) {        maxn[rt]=x;        return;    }    int m=l+r>>1;    if(p<=m)update(p,x,lson);    else update(p,x,rson);    maxn[rt]=max(maxn[rt<<1],maxn[rt<<1|1]);}int query(int a,int b,int l,int r,int rt) {    if(a<=l&&r<=b)return maxn[rt];    int m=l+r>>1;    int ret=0;    if(a<=m)ret=max(ret,query(a,b,lson));    if(b>m)ret=max(ret,query(a,b,rson));    return ret;}int find(int a,int b) {    int f1=top[a],f2=top[b],tmp=0;    while(f1!=f2) {        if(dep[f1]<dep[f2])swap(f1,f2),swap(a,b);        tmp=max(tmp,query(p[f1],p[a],1,cnt,1));        a=fa[f1],f1=top[a];    }    if(a==b)return tmp;    if(dep[a]>dep[b])swap(a,b);    return max(tmp,query(p[son[a]],p[b],1,cnt,1));}int n,u,v,ww,d[N][3];char op[10];void init() {    scanf("%d",&n);    int root=1;    fa[root]=dep[root]=cnt=tot=0;    memset(siz,0,sizeof(siz));    memset(head,-1,sizeof(head));    memset(maxn,0,sizeof(maxn));    for(int i=1; i<n; i++) {        scanf("%d%d%d",&u,&v,&ww);        addedge(u,v,ww);        addedge(v,u,ww);        d[i][0]=u;        d[i][1]=v;        d[i][2]=ww;    }    dfs(root);    build(root,root);    for(int i=1; i<n; i++) {        if(dep[d[i][0]]>dep[d[i][1]])swap(d[i][0],d[i][1]);        update(p[d[i][1]],d[i][2],1,cnt,1);    }}void work() {    while(scanf("%s",op)) {        if(op[0]=='D')break;        int a,b;        scanf("%d%d",&a,&b);        if(op[0]=='Q')printf("%d\n",find(a,b));        else update(p[d[a][1]],b,1,cnt,1);    }}int main() {    int T;    //freopen("f.txt","r",stdin);    scanf("%d",&T);    while(T--) {        init();        work();    }    return 0;}
0 0
原创粉丝点击