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
| #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> #include <set> #define N 100001 #define LL int using namespace std; int t,n,m,ch[N],hr,mi; bool wed[N]; int find_h(vector<LL> *D,LL now,LL no,LL al){ ch[now]=1; int mx=0; for(int i=0;i*2<D[now].size();i++){ if(D[now][i*2]!=no&&!wed[D[now][i*2]]){ int tmp=find_h(D,D[now][i*2],now,al); ch[now]+=tmp; mx=tmp>mx? tmp:mx; } } if(abs(n-ch[now]-mx)<mi){hr=now;mi=abs(n-ch[now]-mx);} return ch[now]; } int DFS(vector<int> *D,vector<int> *S,int lo,int now,int no,int l){ S->push_back(l); LL mx=(*(--lower_bound(++S->begin(),S->begin()+lo,m-l)))+l; for(int i=0;i*2<D[now].size();i++){ LL tmp=0; if(D[now][i*2]!=no&&!wed[D[now][i*2]])tmp=DFS(D,S,lo,D[now][i*2],now,(D[now][i*2+1]+l)%m); mx=(mx>tmp)? mx:tmp; } return mx; } int tre(vector<int> *D,int now,int no){ vector<int>S; vector<int>chc; S.push_back(0); S.push_back(0); S.push_back(0); int lo=S.size(); LL mx=0,tmp=0; for(int i=0;i*2<D[now].size();i++){ hr=D[now][i*2]; if(D[now][i*2]!=no&&!wed[D[now][i*2]])tmp=DFS(D,&S,lo,D[now][i*2],now,D[now][i*2+1]%m); mx=(mx>tmp)? mx:tmp; chc.push_back(S.size()-lo); sort(S.begin(),S.end()); lo=S.size(); } S.clear(); wed[now]=true; int st=0; for(int i=0;i*2<D[now].size();i++){ if(D[now][i*2]!=no&&!wed[D[now][i*2]]){ mi=2147483647; tmp=tre(D,D[now][i*2],0); } mx=(mx>tmp)? mx:tmp; } return mx; } int main(int argc,char * argv[]) { ios_base::sync_with_stdio(false); cin>>t; srand(10248431); while(t--){ fill(wed,wed+N,0); vector<LL>D[N]; cin>>n>>m; for(int i=0;i<n-1;i++){ LL x,y,z; cin>>x>>y>>z; D[x].push_back(y); D[x].push_back(z%m); D[y].push_back(x); D[y].push_back(z%m); } mi=2147483647; find_h(D,1,0,n); cout<<tre(D,hr,0)<<endl; } return 0; }
|