53032023-04-25 17:45:47gortomiTestvérvárosokcpp17Accepted 100/10083ms18992 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;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1892 KiB
2Accepted3ms2088 KiB
subtask215/15
3Accepted3ms2300 KiB
4Accepted3ms2508 KiB
5Accepted3ms2912 KiB
6Accepted3ms3200 KiB
7Accepted3ms3152 KiB
8Accepted3ms3180 KiB
9Accepted3ms3204 KiB
subtask315/15
10Accepted18ms5376 KiB
11Accepted6ms4400 KiB
12Accepted81ms11104 KiB
13Accepted72ms10584 KiB
14Accepted83ms11520 KiB
subtask420/20
15Accepted3ms3804 KiB
16Accepted3ms4080 KiB
17Accepted8ms5516 KiB
18Accepted29ms10716 KiB
19Accepted43ms13572 KiB
20Accepted59ms17156 KiB
21Accepted56ms16396 KiB
22Accepted67ms18992 KiB
subtask550/50
23Accepted75ms11128 KiB
24Accepted39ms7980 KiB
25Accepted54ms8932 KiB
26Accepted12ms5856 KiB
27Accepted39ms8024 KiB
28Accepted79ms11740 KiB
29Accepted75ms11312 KiB
30Accepted75ms11572 KiB
31Accepted83ms12164 KiB