1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| #include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<vector> using namespace std;
typedef long long ll; const int N=150010,M=300010,INF=0x3f3f3f3f; int h[N],e[M],ne[M],w[M],idx; int a[N],n,q,atot; bool vis[N]; ll res;
struct Father{ int zx,now; ll d; }; vector <Father> f[N];
struct Son{ int a;ll d; const bool operator <(const Son &t)const{ return a<t.a; } }; vector <Son> s[N][3];
void add(int a,int b,int c) { e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++; }
int get_size(int x,int fa) { if (vis[x]) return 0; int res=1; for (int i=h[x];~i;i=ne[i]) if (e[i]!=fa) res+=get_size(e[i],x); return res; }
int get_zx(int x,int fa,int tot,int &zx) { if (vis[x]) return 0; int sum=1,maxn=0; for (int i=h[x];~i;i=ne[i]) { if (e[i]==fa) continue; int t=get_zx(e[i],x,tot,zx); maxn=max(maxn,t);sum+=t; } maxn=max(maxn,tot-sum); if (maxn<=tot/2) zx=x; return sum; }
void get_son_tree(int x,int fa,ll d,int zx,int k,vector<Son> &p) { if (vis[x]) return; f[x].push_back((Father){zx,k,d}); p.push_back((Son){a[x],d}); for (int i=h[x];~i;i=ne[i]) if (e[i]!=fa) get_son_tree(e[i],x,d+w[i],zx,k,p); return; }
void calc(int x) { if (vis[x]) return; get_zx(x,-1,get_size(x,-1),x); vis[x]=1; for (int i=h[x],now=0;~i;i=ne[i]) { if (vis[e[i]]) continue; vector<Son> &p=s[x][now]; get_son_tree(e[i],x,w[i],x,now,p); p.push_back((Son){-1,0}); p.push_back((Son){INF,0}); sort(p.begin(),p.end()); for (int i=1;i<p.size();++i) p[i].d+=p[i-1].d; now++; } for (int i=h[x];~i;i=ne[i]) calc(e[i]); }
void query(int x,int l,int r) { res=0; for (int i=0;i<f[x].size();++i) { Father &tmp=f[x][i]; if (a[tmp.zx]>=l&&a[tmp.zx]<=r) res+=tmp.d; for (int now=0;now<3;++now) { vector<Son> &p=s[tmp.zx][now]; if (now==tmp.now||p.empty()) continue; int tl=lower_bound(p.begin(),p.end(),(Son){l,0})-p.begin(), tr=lower_bound(p.begin(),p.end(),(Son){r+1,0})-p.begin(); res+=(tr-tl)*tmp.d+p[tr-1].d-p[tl-1].d; } } for (int now=0;now<3;++now) { vector<Son> &p=s[x][now]; if (p.empty()) continue; int tl=lower_bound(p.begin(),p.end(),(Son){l,0})-p.begin(), tr=lower_bound(p.begin(),p.end(),(Son){r+1,0})-p.begin(); res+=p[tr-1].d-p[tl-1].d; } }
int main() { memset(h,-1,sizeof h); cin>>n>>q>>atot; for (int i=1;i<=n;++i) scanf("%d",a+i); for (int i=1,x,y,c;i<n;++i) { scanf("%d %d %d",&x,&y,&c); add(x,y,c);add(y,x,c); } calc(1); int x,l,r; while (q--) { scanf("%d %d %d",&x,&l,&r); l=(l+res)%atot;r=(r+res)%atot; if (l>r) swap(l,r); query(x,l,r); printf("%lld\n",res); } return 0; }
|