SPOJ_375
树链剖分的处女作终于AC啦,O(∩_∩)O哈哈~
思想是从这篇博客里面学来的:http://blog.sina.com.cn/s/blog_6974c8b20100zc61.html,上面讲得通俗易懂。只不过我在预处理的时候是用他说的避免暴栈的bfs方式来做的。
#include<stdio.h> #include<string.h> #define MAXD 10010 #define MAXM 20010 #define NINF 0xc3c3c3c3 int N, cnt, first[MAXD], e, next[MAXM], v[MAXM], fa[MAXD], dep[MAXD], size[MAXD], son[MAXD], top[MAXD], w[MAXD], max[4 * MAXD]; int q[MAXD]; struct Edge { int x, y, z; }edge[MAXD]; int Max(int x, int y) { return x > y ? x : y; } void Swap(int &x, int &y) { int t; t = x, x = y, y = t; } void add(int x, int y) { v[e] = y; next[e] = first[x], first[x] = e ++; } void prepare() { int i, j, k, x, y, rear = 0; q[rear ++] = 1; dep[1] = 1, fa[1] = 0, son[1] = 0; for(i = 0; i < rear; i ++) { x = q[i]; for(j = first[x]; j != -1; j = next[j]) if(v[j] != fa[x]) { fa[v[j]] = x, dep[v[j]] = dep[x] + 1; q[rear ++] = v[j]; } } size[0] = 0; for(i = rear - 1; i >= 0; i --) { x = q[i]; size[x] = 1, son[x] = 0; for(j = first[x]; j != -1; j = next[j]) if(v[j] != fa[x]) { size[x] += size[v[j]]; if(size[v[j]] > size[son[x]]) son[x] = v[j]; } } cnt = 0; memset(top, 0, sizeof(top)); for(i = 0; i < rear; i ++) { x = q[i]; if(!top[x]) { for(y = x; y != 0; y = son[y]) { top[y] = x; w[y] = ++ cnt; } } } } void update(int cur) { max[cur] = Max(max[cur << 1], max[cur << 1 | 1]); } void refresh(int cur, int x, int y, int k, int v) { int mid = (x + y) >> 1, ls = cur << 1, rs = cur << 1 | 1; if(x == y) { max[cur] = v; return ; } if(k <= mid) refresh(ls, x, mid, k, v); else refresh(rs, mid + 1, y, k, v); update(cur); } void init() { int i, x, y, z; e = 0; memset(first, -1, sizeof(first)); scanf("%d", &N); for(i = 1; i < N; i ++) { scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].z); add(edge[i].x, edge[i].y), add(edge[i].y, edge[i].x); } prepare(); memset(max, 0xc3, sizeof(max)); for(i = 1; i < N; i ++) { if(dep[edge[i].x] > dep[edge[i].y]) Swap(edge[i].x, edge[i].y); refresh(1, 1, N, w[edge[i].y], edge[i].z); } } void query(int cur, int x, int y, int s, int t, int &ans) { int mid = (x + y) >> 1, ls = cur << 1, rs = cur << 1 | 1; if(x >= s && y <= t) { ans = Max(ans, max[cur]); return ; } if(mid >= s) query(ls, x, mid, s, t, ans); if(mid + 1 <= t) query(rs, mid + 1, y, s, t, ans); } void Query(int x, int y) { int fx = top[x], fy = top[y], ans = NINF; while(fx != fy) { if(dep[fx] > dep[fy]) Swap(fx, fy), Swap(x, y); query(1, 1, N, w[fy], w[y], ans); y = fa[fy], fy = top[y]; } if(x != y) { if(dep[x] > dep[y]) Swap(x, y); query(1, 1, N, w[son[x]], w[y], ans); } printf("%d\n", ans); } void solve() { int i, x, y; char op[10]; for(;;) { scanf("%s", op); if(op[0] == 'D') break; scanf("%d%d", &x, &y); if(op[0] == 'C') refresh(1, 1, N, w[edge[x].y], y); else Query(x, y); } } int main() { int t; scanf("%d", &t); while(t --) { init(); solve(); } return 0; }