SPOJ - QTREE2 Query on a tree II树链剖分

本文介绍了一种使用树链剖分技术解决SPOJ QTREE2问题的方法,该问题涉及查询树中两点间的距离及路径上的特定节点。通过树链剖分,可以有效地处理这类查询,提高查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SPOJ - QTREE2 Query on a tree II

You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, 3...N-1. Each edge has an integer value assigned to it, representing its length. 
We will ask you to perfrom some instructions of the following form: 
DIST a b : ask for the distance between node a and node b
or 
KTH a b k : ask for the k-th node on the path from node a to node b 
Example:
N = 6 
1 2 1 // edge connects node 1 and node 2 has cost 1 
2 4 1 
2 5 2 
1 3 1 
3 6 2 

Path from node 4 to node 6 is 4 -> 2 -> 1 -> 3 -> 6 
DIST 4 6 : answer is 5 (1 + 1 + 1 + 2 = 5) 
KTH 4 6 4 : answer is 3 (the 4-th node on the path from node 4 to node 6 is 3) 
Input
The first line of input contains an integer t, the number of test cases (t <= 25). t test cases follow. 
For each test case:
In the first line there is an integer N (N <= 10000) 
In the next N-1 lines, the i-th line describes the i-th edge: a line with three integers a b c denotes an edge between a, b of cost c (c <= 100000) 
The next lines contain instructions "DIST a b" or "KTH a b k" 
The end of each test case is signified by the string "DONE". 
There is one blank line between successive tests. 
Output
For each "DIST" or "KTH" operation, write one integer representing its result.
Print one blank line after each test. 
Example
Input:
1

6
1 2 1
2 4 1
2 5 2
1 3 1
3 6 2
DIST 4 6
KTH 4 6 4
DONE

Output:
5
3

题意:
给一棵树,维护两点间距离和路径上第k的结点的编号。
解:
树链剖分。
在求KTH时,由于遍历过程根据路径左右两端结点所在重链深度来回跳,故设置一个flag(flag=0从起点向上拉的链,flag=1从终点向上拉的链)记录现在爬的是左边还是右边的重链。
flag有两种情况会改变:
(1)交换x, y
(2)循环top[x] != top[y]结束时。因为此时,假设flag=1,则意味着从终点拉的链连到了起点多次跳转后所在的重链上(假设跳转到同一条重链上时,起点在终点下方),则此时是从起点向上跳,flag变为0。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 1000000 + 10;

struct Edge{
    int t, w, id;
    Edge(int a=0, int b=0, int c=0):t(a), w(b), id(c){}
};

int n;
vector<Edge> map[MAXN];

struct rmq{
    int w[MAXN], tree[MAXN << 2];

    void build(int l, int r, int id) {
        if (l == r) {
          tree[id] = w[l];
          return;
        }
        int mid = l + r >> 1;
        build(l, mid, id << 1);
        build(mid + 1, r, (id << 1) + 1);
        tree[id] = tree[id << 1] + tree[(id << 1) + 1];
    }

    int query(int l, int r, int a, int b, int id) {
        if (a <= l && r <= b) return tree[id];
        int mid = l + r >> 1, res = 0;
        if (a <= mid && l <= b) res += query(l, mid, a, b, id << 1);
        if (mid < b && a <= r) res += query(mid+1, r, a, b, (id << 1) + 1);
        return res;
    }
}RMQ;

struct chainDivide{
    int fa[MAXN], dep[MAXN], son[MAXN], size[MAXN], top[MAXN], w[MAXN], tid[MAXN], bid[MAXN];
    int tot;

    void find(int x, int father, int depth) {
        fa[x] = father;
        son[x] = 0;
        size[x] = 1;
        dep[x] = depth;
        int maxsize = 0;
        for (int i = 0; i < map[x].size(); ++i) {
          Edge cur = map[x][i];
          if (cur.t == father) continue;
          find(cur.t, x, depth + 1);
          size[x] += size[cur.t];
          w[cur.t] = cur.w;
          if (maxsize < size[cur.t]) {
            maxsize = size[cur.t];
            son[x] = cur.t;
          }
        }
    }

    void connect(int x, int ancestor) {
        top[x] = ancestor;
        tid[x] = ++tot;
        if (son[x]) {
          connect(son[x], ancestor);
          for (int i = 0; i < map[x].size(); ++i) {
            Edge cur = map[x][i];
            if (tid[cur.t]) continue;
            connect(cur.t, cur.t);
          }
        }
    }

    int query(int x, int y) {
        int res = 0;
        while (top[x] != top[y]) {
          if (dep[top[x]] < dep[top[y]]) swap(x, y);
          res += RMQ.query(1, n, tid[top[x]], tid[x], 1);
          x = fa[top[x]];
        }
        if (dep[x] > dep[y]) swap(x, y);
        res += RMQ.query(1, n, tid[x]+1, tid[y], 1);
        return res; 
    }   

    int query2(int x, int y, int k) {
        vector<int> bri[2];
        int flag = 0;
        while (top[x] != top[y]) {
          if (dep[top[x]] < dep[top[y]]) swap(x, y), flag ^= 1;
          for (int i = tid[x]; i >= tid[top[x]]; --i) bri[flag].push_back(bid[i]);
          x = fa[top[x]];
        }   
        flag ^= 1;  
        if (dep[x] > dep[y]) swap(x, y), flag ^= 1;
        for (int i = tid[y]; i >= tid[x]; --i) bri[flag].push_back(bid[i]);
        if (bri[0].size() >= k) return bri[0][k-1];
        else return bri[1][bri[1].size()+bri[0].size()-k];
    }

    void init() {
        memset(tid, 0, sizeof tid);
        w[1] = tot = 0;
        find(1, 0, 1);
        connect(1, 1);
        for (int i = 1; i <= n; ++i) {
          RMQ.w[tid[i]] = w[i];
          bid[tid[i]] = i;
        }
        RMQ.build(1, n, 1);
    }
}CD;

char s[20];

int main()
{
    freopen("in.txt", "r", stdin);
    int T, a, b, c;
    scanf("%d", &T);
    while (T--) {
      scanf("%d", &n);
      for (int i = 1; i <= n; ++i) map[i].clear();
      for (int i = 1; i < n; ++i) {
        scanf("%d%d%d", &a, &b, &c);
        map[a].push_back(Edge(b, c, i));
        map[b].push_back(Edge(a, c, i));
      }
      CD.init();
      while (scanf("%s", s) && s[1] != 'O') {
        scanf("%d%d", &a, &b);
        if (s[0] == 'D')
          printf("%d\n", CD.query(a, b));
        else {
          scanf("%d", &c);
          printf("%d\n", CD.query2(a, b, c));
        }
      }
    }
    return 0;
} 
资源下载链接为: https://pan.quark.cn/s/1bfadf00ae14 华为移动服务(Huawei Mobile Services,简称 HMS)是一个全面开放的移动服务生态系统,为企业和开发者提供了丰富的工具和 API,助力他们构建、运营和推广应用。其中,HMS Scankit 是华为推出的一款扫描服务 SDK,支持快速集成到安卓应用中,能够提供高效且稳定的二维码和条形码扫描功能,适用于商品扫码、支付验证、信息获取等多种场景。 集成 HMS Scankit SDK 主要包括以下步骤:首先,在项目的 build.gradle 文件中添加 HMS Core 库和 Scankit 依赖;其次,在 AndroidManifest.xml 文件中添加相机访问和互联网访问权限;然后,在应用程序的 onCreate 方法中调用 HmsClient 进行初始化;接着,可以选择自定义扫描界面或使用 Scankit 提供的默认扫描界面;最后,实现 ScanCallback 接口以处理扫描成功和失败的回调。 HMS Scankit 内部集成了开源的 Zxing(Zebra Crossing)库,这是一个功能强大的条码和二维码处理库,提供了解码、生成、解析等多种功能,既可以单独使用,也可以与其他扫描框架结合使用。在 HMS Scankit 中,Zxing 经过优化,以更好地适应华为设备,从而提升扫描性能。 通常,ScanKitDemoGuide 包含了集成 HMS Scankit 的示例代码,涵盖扫描界面的布局、扫描操作的启动和停止以及扫描结果的处理等内容。开发者可以参考这些代码,快速掌握在自己的应用中实现扫码功能的方法。例如,启动扫描的方法如下: 处理扫描结果的回调如下: HMS Scankit 支持所有安卓手机,但在华为设备上能够提供最佳性能和体验,因为它针对华为硬件进行了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值