102032024-03-29 13:35:08111Testvérvárosokcpp17Accepted 100/100101ms37932 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);
			ans+=z[x%K];
			if(z.size()>s.size()){
				swap(s,z);
			}
			for(auto[y,c]:z){
				ans+=s[((x*2-y)%K+K)%K]*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
1Accepted3ms1832 KiB
2Accepted3ms2068 KiB
subtask215/15
3Accepted3ms2284 KiB
4Accepted3ms2608 KiB
5Accepted4ms2924 KiB
6Accepted4ms3184 KiB
7Accepted3ms2888 KiB
8Accepted3ms2992 KiB
9Accepted4ms3524 KiB
subtask315/15
10Accepted10ms4980 KiB
11Accepted4ms5000 KiB
12Accepted37ms10708 KiB
13Accepted32ms10240 KiB
14Accepted37ms11260 KiB
subtask420/20
15Accepted3ms3892 KiB
16Accepted3ms4416 KiB
17Accepted8ms7584 KiB
18Accepted20ms18828 KiB
19Accepted29ms25732 KiB
20Accepted37ms34000 KiB
21Accepted29ms32004 KiB
22Accepted45ms37932 KiB
subtask550/50
23Accepted90ms13504 KiB
24Accepted52ms9792 KiB
25Accepted64ms10568 KiB
26Accepted46ms6820 KiB
27Accepted48ms10036 KiB
28Accepted76ms12864 KiB
29Accepted97ms12900 KiB
30Accepted32ms11756 KiB
31Accepted101ms13964 KiB