Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define ll long long int
- using namespace std;
- vector<pair<int,int> > v[100005];
- ll sz[100005];
- int arr[100005];
- ll ans[100005];
- void pehle()
- {
- for(int i=0;i<=100000;i++)
- {
- arr[i]=i;
- sz[i]=1;
- }
- }
- int root(int a)
- {
- while(arr[a]!=a)
- {
- arr[a]=arr[arr[a]];
- a=arr[a];
- }
- return a;
- }
- void join(int a,int b)
- {
- int x=root(a);
- int y=root(b);
- if(x!=y)
- {
- if(sz[x]<sz[y])
- {
- arr[x]=y;
- sz[y]+=sz[x];
- }
- else
- {
- arr[y]=x;
- sz[x]+=sz[y];
- }
- }
- }
- int main()
- {
- int n,q;
- cin>>n>>q;
- int x,y,w;
- for(int i=0;i<n-1;i++)
- {
- cin>>x>>y>>w;
- for(int j=1;j<=sqrt(w);j++)
- {
- if(w%j==0)
- {
- if(w%j==j)
- {
- v[j].push_back({x,y});
- }
- else
- {
- v[j].push_back({x,y});
- v[w/j].push_back({x,y});
- }
- }
- }
- }
- pehle();
- for(int i=1;i<=100000;i++)
- {
- ll gg=0;
- for(auto it : v[i])
- {
- join(it.first,it.second);
- }
- for(auto it : v[i])
- {
- arr[it.first]=it.first;
- arr[it.second]=it.second;
- int s=sz[it.first];
- gg+=(s*(s-1))/2;
- int g=sz[it.second];
- gg+=(g*(g-1))/2;
- sz[it.first]=1;
- sz[it.second]=1;
- }
- ans[i]=gg;
- }
- while(q--)
- {
- int k;
- cin>>k;
- cout<<ans[k]<<"\n";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment