53012023-04-25 17:33:10gortomiTestvérvárosokcpp17Wrong answer 0/1001.575s11564 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)
{
    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;
    c = s[n];
    dfs(n, 0);
    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
2Wrong answer3ms2128 KiB
subtask20/15
3Wrong answer3ms2336 KiB
4Accepted3ms2552 KiB
5Wrong answer4ms2912 KiB
6Wrong answer4ms3128 KiB
7Wrong answer4ms3208 KiB
8Accepted3ms3156 KiB
9Wrong answer6ms3512 KiB
subtask30/15
10Wrong answer187ms5156 KiB
11Accepted301ms4384 KiB
12Wrong answer1.133s10488 KiB
13Wrong answer1.449s9832 KiB
14Wrong answer1.32s10364 KiB
subtask40/20
15Accepted4ms4096 KiB
16Accepted29ms4176 KiB
17Accepted1.125s5764 KiB
18Time limit exceeded1.575s6460 KiB
19Time limit exceeded1.572s7884 KiB
20Time limit exceeded1.557s9800 KiB
21Time limit exceeded1.572s9552 KiB
22Time limit exceeded1.569s10704 KiB
subtask50/50
23Time limit exceeded1.569s6808 KiB
24Wrong answer628ms7956 KiB
25Wrong answer800ms9056 KiB
26Wrong answer12ms5868 KiB
27Wrong answer644ms7956 KiB
28Wrong answer1.144s11200 KiB
29Wrong answer949ms10944 KiB
30Wrong answer1.228s10888 KiB
31Wrong answer1.294s11564 KiB