标签:des style blog color os io strong for ar
Time Limit: 4000MS | Memory Limit: 65536K | |
Total Submissions: 5798 | Accepted: 1455 |
Description
Input
Output
Sample Input
3 3 1 1 2 1 2 3 2 0 2 1 2 3 0 3
Sample Output
1 3
树链剖分 ,边上有权 ,单点更新,区间查询
#include <cstdio> #include <queue> #include <algorithm> #include <iostream> #include <cstring> using namespace std; #define root 1,n,1 #define lr rt<<1 #define rr rt<<1|1 #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef long long LL; const int N= 100100; int n,q,s; int eh[N],et[N<<2],nxt[N<<2],w[N<<2],tot=0; int pos,p[N],top[N],rnk[N],dep[N],fa[N],son[N],siz[N]; struct node { int u,v,w; }e[N<<2]; void init() { memset(eh,-1,sizeof(eh)); memset(son,-1,sizeof(son)); tot=0; pos=0; } void addedge(int u,int v){ et[tot]=v;nxt[tot]=eh[u];eh[u]=tot++; et[tot]=u;nxt[tot]=eh[v];eh[v]=tot++; } void dfs1(int u,int father,int d) { dep[u]=d; fa[u]=father; siz[u]=1; for(int i=eh[u];~i;i=nxt[i]){ int v=et[i]; if(v != father){ dfs1(v,u,d+1); siz[u] += siz[v]; if( son[u]==-1 || siz[v] > siz[son[u]]) son[u]=v; } } } void dfs2(int u,int tp) { top[u]=tp; p[u]= ++pos; rnk[ p[u] ]= u; if( son[u] == -1 )return ; dfs2(son[u], tp ); for(int i=eh[u]; ~i ;i=nxt[i]){ int v=et[i]; if(v != son[u] && v!=fa[u] ){ dfs2(v,v); } } } int sum[ N<<2 ]; void Up(int rt) { sum[rt]=sum[lr]+sum[rr]; } void build(int l,int r,int rt) { if(l == r ){ sum[rt]=0; return ; } int m=(l+r)>>1; build(lson); build(rson); Up(rt); } void update(int l,int r,int rt,int x,int v) { if( l == r ){ sum[rt]=v; return ; } int m=(l+r)>>1; if(x<=m) update(lson,x,v); if(x>m) update(rson,x,v); Up(rt); } int query(int l,int r,int rt,int L,int R) { int res=0; if( L<=l&&r<=R ){ return sum[rt]; } int m=(l+r)>>1; if(L <= m) res += query(lson,L,R); if(R > m) res += query(rson,L,R); return res; } int Q(int u,int v) { int res=0; int f1=top[u],f2=top[v]; while(f1 != f2){ if(dep[f1] < dep[f2]){ swap(f1,f2); swap(u,v); } res += query(root,p[f1],p[u]); u=fa[f1]; f1=top[u]; } if(u==v)return res; if(dep[u]>dep[v])swap(u,v); res += query(root,p[son[u]],p[v]); return res; } int run() { int u,v,w; int op; while(~scanf("%d%d%d",&n,&q,&s)){ init(); for(int i= 0;i<n-1;++i){ scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w); addedge(e[i].u,e[i].v); } dfs1(1,0,0); dfs2(1,1); build(root); for(int i=0;i<n-1;++i) { if(dep[e[i].u] > dep[e[i].v]) swap(e[i].u,e[i].v); update(root,p[e[i].v],e[i].w); } while(q--) { scanf("%d",&op); if( !op ) { scanf("%d",&u); printf("%d\n",Q(s,u)); s=u; } else { scanf("%d%d",&v,&w); update(root,p[ e[v-1].v ],w); } } } return 0; } int main() { //freopen("in.txt","r",stdin); ios::sync_with_stdio(0); return run(); }
标签:des style blog color os io strong for ar
原文地址:http://www.cnblogs.com/YRETSIM/p/3932240.html