5302 2023. 04. 25 17:41:31 gortomi Testvérvárosok cpp17 Time limit exceeded 15/100 1.574s 12384 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;
}
Subtask Sum Test Verdict Time Memory
subtask1 0/0
1 Accepted 3ms 1892 KiB
2 Accepted 3ms 2132 KiB
subtask2 15/15
3 Accepted 3ms 2472 KiB
4 Accepted 3ms 2476 KiB
5 Accepted 4ms 2888 KiB
6 Accepted 4ms 3096 KiB
7 Accepted 4ms 3172 KiB
8 Accepted 3ms 3096 KiB
9 Accepted 6ms 3400 KiB
subtask3 0/15
10 Accepted 192ms 5272 KiB
11 Accepted 307ms 4356 KiB
12 Accepted 1.194s 10960 KiB
13 Time limit exceeded 1.542s 10520 KiB
14 Accepted 1.37s 11508 KiB
subtask4 0/20
15 Accepted 6ms 4016 KiB
16 Accepted 30ms 4376 KiB
17 Accepted 1.162s 5876 KiB
18 Time limit exceeded 1.557s 6656 KiB
19 Time limit exceeded 1.567s 8404 KiB
20 Time limit exceeded 1.565s 10408 KiB
21 Time limit exceeded 1.574s 10004 KiB
22 Time limit exceeded 1.56s 11464 KiB
subtask5 0/50
23 Time limit exceeded 1.559s 7564 KiB
24 Accepted 671ms 8572 KiB
25 Accepted 847ms 9576 KiB
26 Accepted 12ms 6104 KiB
27 Accepted 675ms 8480 KiB
28 Accepted 1.185s 12120 KiB
29 Accepted 980ms 11756 KiB
30 Accepted 1.299s 11860 KiB
31 Accepted 1.371s 12384 KiB