标签:include tput clu math tin for ios amp eve
Time Limit: 4000MS | Memory Limit: 65536K | |
Total Submissions: 10378 | Accepted: 2886 |
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
树链剖分水题。建议在POJ上用C++交,用G++可能会超时。
#include <iostream> #include <cstring> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <time.h> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #define met(a,b) memset(a,b,sizeof a) #define pb push_back #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; typedef long long ll; const int N=2e5+50; const int M=N*N+10; int dep[N],siz[N],fa[N],id[N],son[N],val[N],top[N]; //top 最近的重链父节点 int num,s,m,n,q; int sum[N*2],tre[2*N]; vector<int> v[N]; struct tree { int x,y,val; void read() { scanf("%d%d%d",&x,&y,&val); } }e[N]; void dfs1(int u, int f, int d) { dep[u] = d; siz[u] = 1; son[u] = 0; fa[u] = f; for (int i = 0; i < v[u].size(); i++) { int ff = v[u][i]; if (ff == f) continue; dfs1(ff, u, d + 1); siz[u] += siz[ff]; if (siz[son[u]] < siz[ff]) son[u] = ff; } } void dfs2(int u, int tp) { top[u] = tp; id[u] = ++num; if (son[u]) dfs2(son[u], tp); for (int i = 0; i < v[u].size(); i++) { int ff = v[u][i]; if (ff == fa[u] || ff == son[u]) continue; dfs2(ff, ff); } } inline void PushPlus(int rt) { sum[rt]=sum[rt*2]+sum[rt*2+1]; } void Build(int l,int r,int rt) { if(l==r) { sum[rt]=val[l]; return; } int m=(l+r)>>1; Build(lson); Build(rson); PushPlus(rt); //printf("rt=%d sum[rt]=%d\n",rt,sum[rt]); } void Update(int p,int add,int l,int r,int rt) { if(l==r) { sum[rt]=add; return; } int m=(r+l)>>1; if(p<=m)Update(p,add,lson); else Update(p,add,rson); PushPlus(rt); } int Query(int L,int R,int l,int r,int rt) { if(L<=l&&r<=R)return sum[rt]; int m=(l+r)>>1; int ans=0; if(L<=m)ans+=Query(L,R,lson); if(R>m)ans+=Query(L,R,rson); return ans; } int Yougth(int u, int v) { int tp1 = top[u], tp2 = top[v]; int ans = 0; while (tp1 != tp2) { if (dep[tp1] < dep[tp2]) { swap(tp1, tp2); swap(u, v); } ans += Query(id[tp1], id[u],1,n,1); u = fa[tp1]; tp1 = top[u]; } if (u == v) return ans; if (dep[u] > dep[v]) swap(u, v); ans += Query(id[son[u]], id[v],1,n,1); return ans; } void Clear(int n) { for(int i=1; i<=n; i++) v[i].clear(); } int main() { int u,vv,w; scanf("%d%d%d",&n,&q,&s); for(int i=1; i<n; i++) { e[i].read(); v[e[i].x].push_back(e[i].y); v[e[i].y].push_back(e[i].x); } num = 0; dfs1(1,0,1); dfs2(1,1); for (int i = 1; i < n; i++) { if (dep[e[i].x] < dep[e[i].y]) swap(e[i].x, e[i].y); val[id[e[i].x]] = e[i].val; } Build(1,num,1); while(q--) { int x; scanf("%d",&x); if(!x){ scanf("%d",&u); printf("%d\n",Yougth(s,u)); s=u; } else { scanf("%d%d",&u,&vv); Update(id[e[u].x],vv,1,n,1); } } Clear(n); return 0; }
POJ 2763 Housewife Wind(树链剖分)(线段树单点修改)
标签:include tput clu math tin for ios amp eve
原文地址:http://www.cnblogs.com/jianrenfang/p/6357573.html