53022023-04-25 17:41:31gortomiTestvérvárosokcpp17Time limit exceeded 15/1001.574s12384 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)
{
    w[n] = 1;
    dfs(n, 0);
    c = s[n];
    int u = fc(n, 0);
    dep[0]++;
    to.clear();
    for(auto x : g[n])
    {
        int y = x.first;
        if(!w[y])
        {
            act.clear();
            d[y] = x.second % k;
            add(y, n);
            for(auto x : act)
            {
                dep[d[x]]++;
            }
        }
    }
    for(auto x : to) dep[d[x]]--;
    dep[0]--;
    for(auto x : g[n])
    {
        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
2Accepted3ms2132 KiB
subtask215/15
3Accepted3ms2472 KiB
4Accepted3ms2476 KiB
5Accepted4ms2888 KiB
6Accepted4ms3096 KiB
7Accepted4ms3172 KiB
8Accepted3ms3096 KiB
9Accepted6ms3400 KiB
subtask30/15
10Accepted192ms5272 KiB
11Accepted307ms4356 KiB
12Accepted1.194s10960 KiB
13Time limit exceeded1.542s10520 KiB
14Accepted1.37s11508 KiB
subtask40/20
15Accepted6ms4016 KiB
16Accepted30ms4376 KiB
17Accepted1.162s5876 KiB
18Time limit exceeded1.557s6656 KiB
19Time limit exceeded1.567s8404 KiB
20Time limit exceeded1.565s10408 KiB
21Time limit exceeded1.574s10004 KiB
22Time limit exceeded1.56s11464 KiB
subtask50/50
23Time limit exceeded1.559s7564 KiB
24Accepted671ms8572 KiB
25Accepted847ms9576 KiB
26Accepted12ms6104 KiB
27Accepted675ms8480 KiB
28Accepted1.185s12120 KiB
29Accepted980ms11756 KiB
30Accepted1.299s11860 KiB
31Accepted1.371s12384 KiB