5303 | 2023-04-25 17:45:47 | gortomi | Testvérvárosok | cpp17 | Accepted 100/100 | 83ms | 18992 KiB |
#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > g;
vector<int> d, s, act, to, dep;
long long ans = 0;
int k, c;
vector<bool> w;
void dfs(int n, int p)
{
s[n] = 1;
for(auto x : g[n])
{
int y = x.first;
if(y != p && !w[y])
{
dfs(y, n);
s[n] += s[y];
}
}
}
int fc(int n, int p)
{
for(auto x : g[n])
{
int y = x.first;
if(!w[y] && y != p)
{
if(s[y] > c / 2) return fc(y, n);
}
}
return n;
}
void add(int n, int p)
{
act.push_back(n);
to.push_back(n);
ans += dep[(k - d[n]) % k];
for(auto x : g[n])
{
int y = x.first;
if(!w[y] && y != p)
{
d[y] = (d[n] + x.second) % k;
add(y, n);
}
}
}
void solve(int n)
{
dfs(n, 0);
c = s[n];
int u = fc(n, 0);
w[u] = 1;
dep[0]++;
to.clear();
for(auto x : g[u])
{
int y = x.first;
if(!w[y])
{
act.clear();
d[y] = x.second % k;
add(y, u);
for(auto x : act)
{
dep[d[x]]++;
}
}
}
for(auto x : to) dep[d[x]]--;
dep[0]--;
for(auto x : g[u])
{
int y = x.first;
if(!w[y]) solve(y);
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n >> k;
g.resize(n + 1);
d.resize(n + 1);
w.resize(n + 1);
s.resize(n + 1);
dep.resize(k);
for(int i = 0; i < n - 1; i++)
{
int x, y, w;
cin >> x >> y >> w;
g[x].push_back({y, w});
g[y].push_back({x, w});
}
solve(1);
cout << ans;
}
Subtask | Sum | Test | Verdict | Time | Memory | ||
---|---|---|---|---|---|---|---|
subtask1 | 0/0 | ||||||
1 | Accepted | 3ms | 1892 KiB | ||||
2 | Accepted | 3ms | 2088 KiB | ||||
subtask2 | 15/15 | ||||||
3 | Accepted | 3ms | 2300 KiB | ||||
4 | Accepted | 3ms | 2508 KiB | ||||
5 | Accepted | 3ms | 2912 KiB | ||||
6 | Accepted | 3ms | 3200 KiB | ||||
7 | Accepted | 3ms | 3152 KiB | ||||
8 | Accepted | 3ms | 3180 KiB | ||||
9 | Accepted | 3ms | 3204 KiB | ||||
subtask3 | 15/15 | ||||||
10 | Accepted | 18ms | 5376 KiB | ||||
11 | Accepted | 6ms | 4400 KiB | ||||
12 | Accepted | 81ms | 11104 KiB | ||||
13 | Accepted | 72ms | 10584 KiB | ||||
14 | Accepted | 83ms | 11520 KiB | ||||
subtask4 | 20/20 | ||||||
15 | Accepted | 3ms | 3804 KiB | ||||
16 | Accepted | 3ms | 4080 KiB | ||||
17 | Accepted | 8ms | 5516 KiB | ||||
18 | Accepted | 29ms | 10716 KiB | ||||
19 | Accepted | 43ms | 13572 KiB | ||||
20 | Accepted | 59ms | 17156 KiB | ||||
21 | Accepted | 56ms | 16396 KiB | ||||
22 | Accepted | 67ms | 18992 KiB | ||||
subtask5 | 50/50 | ||||||
23 | Accepted | 75ms | 11128 KiB | ||||
24 | Accepted | 39ms | 7980 KiB | ||||
25 | Accepted | 54ms | 8932 KiB | ||||
26 | Accepted | 12ms | 5856 KiB | ||||
27 | Accepted | 39ms | 8024 KiB | ||||
28 | Accepted | 79ms | 11740 KiB | ||||
29 | Accepted | 75ms | 11312 KiB | ||||
30 | Accepted | 75ms | 11572 KiB | ||||
31 | Accepted | 83ms | 12164 KiB |