102062024-03-29 13:39:40111Testvérvárosokcpp17Accepted 100/10071ms36460 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int N,K;
	cin>>N>>K;
	vector<vector<pair<int,int>>>g(N+1);
	for(int i=0;i<N-1;i++){
		int a,b,d;
		cin>>a>>b>>d;
		g[a].emplace_back(b,d);
		g[b].emplace_back(a,d);
	}
	int ans=0;
	auto dfs=[&](auto self,int i,int p,int x)->map<int,int>{
		map<int,int>s;
		for(auto[j,d]:g[i]){
			if(j==p){
				continue;
			}
			auto z=self(self,j,i,x+d);
			auto q=z.find(x%K);
			if(q!=z.end())ans+=q->second;
			if(z.size()>s.size()){
				swap(s,z);
			}
			for(auto[y,c]:z){
				auto q=s.find(((x*2-y)%K+K)%K);
				if(q!=s.end())ans+=q->second*c;
			}
			for(auto[y,c]:z){
				s[y]+=c;
			}
		}
		s[x%K]++;
		return s;
	};
	dfs(dfs,1,0,0);
	cout<<ans<<'\n';
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1824 KiB
2Accepted3ms2072 KiB
subtask215/15
3Accepted3ms2244 KiB
4Accepted3ms2456 KiB
5Accepted3ms2872 KiB
6Accepted4ms3164 KiB
7Accepted3ms3328 KiB
8Accepted3ms3604 KiB
9Accepted4ms3908 KiB
subtask315/15
10Accepted10ms5752 KiB
11Accepted4ms5936 KiB
12Accepted48ms11768 KiB
13Accepted32ms11456 KiB
14Accepted39ms12192 KiB
subtask420/20
15Accepted3ms4732 KiB
16Accepted3ms5184 KiB
17Accepted8ms8240 KiB
18Accepted23ms18892 KiB
19Accepted29ms25136 KiB
20Accepted39ms32868 KiB
21Accepted32ms30592 KiB
22Accepted48ms36460 KiB
subtask550/50
23Accepted64ms12656 KiB
24Accepted37ms9076 KiB
25Accepted46ms9924 KiB
26Accepted18ms6368 KiB
27Accepted35ms9388 KiB
28Accepted59ms12528 KiB
29Accepted67ms12252 KiB
30Accepted34ms11600 KiB
31Accepted71ms13312 KiB