func_code_string: #include <bits/stdc++.h>   using namespace std;   int n, Q, x, y, z, kk;   int dis[500005], head[500005], father[500005], top[500005], q[500005];   bool vis[500005];   int far[500005], heavyson[500005], rak[500005], sum[500005], leaf[500005], ans,       d[500005];   struct Tree {     int nxt, to, step;   } e[500005];   inline bool cmp(int u, int v) {     return dis[u] - dis[father[top[u]]] > dis[v] - dis[father[top[v]]];   }   inline void link(int x, int y, int z) {     e[++kk].nxt = head[x];     e[kk].to = y;     e[kk].step = z;     head[x] = kk;   }   inline int bfs(int S) {     int left1 = 1;     int right1 = 1;     q[left1] = S;     memset(d, 0, sizeof(d));     memset(vis, false, sizeof(vis));     vis[S] = true;     while (left1 <= right1) {       int u = q[left1++];       for (int i = head[u]; i; i = e[i].nxt) {         int v = e[i].to;         if (vis[v]) continue;         vis[v] = true;         q[++right1] = v;         d[v] = d[u] + e[i].step;       }     }     int kkk = 0;     for (int i = 1; i <= n; i++) {       if (d[i] > d[kkk]) kkk = i;     }     return kkk;   }   void dfs1(int u, int fa) {     far[u] = dis[u];     for (int i = head[u]; i; i = e[i].nxt) {       int v = e[i].to;       if (v == fa) continue;       father[v] = u;       dis[v] = dis[u] + e[i].step;       dfs1(v, u);       if (!heavyson[u] || far[u] < far[v]) heavyson[u] = v, far[u] = far[v];     }   }   void dfs2(int u, int first) {     top[u] = first;     if (!heavyson[u]) {       leaf[++leaf[0]] = u;       return;     }     dfs2(heavyson[u], first);     for (int i = head[u]; i; i = e[i].nxt) {       int v = e[i].to;       if (v == father[u] || v == heavyson[u]) continue;       dfs2(v, v);     }   }   inline int solve(int x, int y) {     if (rak[top[x]] <= 2 * y - 1) return sum[min(y * 2 - 1, leaf[0])];     int u = x;     while (rak[top[u]] > y * 2 - 1) u = father[top[u]];     return sum[y * 2 - 1] -            min(min(sum[y * 2 - 1] - sum[y * 2 - 2], far[u] - dis[u]), dis[u]) +            far[x] - dis[u];   }   int main() {     scanf( %d%d , &n, &Q);     for (int i = 1; i < n; i++) {       scanf( %d%d%d , &x, &y, &z);       link(x, y, z);       link(y, x, z);     }     int first = bfs(1);     int root = bfs(first);     dfs1(root, -1);     dfs2(root, root);     sort(leaf + 1, leaf + leaf[0] + 1, cmp);     for (int i = 1; i <= leaf[0]; i++) {       rak[top[leaf[i]]] = i;       sum[i] = sum[i - 1] + dis[leaf[i]] - dis[father[top[leaf[i]]]];     }     while (Q--) {       scanf( %d%d , &x, &y);       x = ((x + ans - 1) % n) + 1;       y = ((y + ans - 1) % n) + 1;       printf( %d n , ans = solve(x, y));     }     return 0;   }   