49482023-04-07 18:52:52zsomborTestvérvárosokcpp17Accepted 100/100180ms17196 KiB
#include <iostream>
#include <vector>
using namespace std;
using ll = long long;

struct edge {
    int to, w;
    edge(int TO, int W) {
        to = TO;
        w = W;
    }
};

int n, k, c, sz;
ll wsum, ans = 0;
vector <bool> volt(5e4 + 1, false);
vector <vector <edge>> g(5e4 + 1);
vector <int> cnt(1e3, 0);

int get_c(int x) {
    if (volt[x]) return 0;
    volt[x] = true;
    int cur, sum = 1;
    bool cen = true;
    for (edge e : g[x]) {
        cur = get_c(e.to);
        sum += cur;
        if (cur > sz / 2) cen = false;
    }
    if (sz - sum > sz / 2) cen = false;
    if (cen) c = x;
    volt[x] = false;
    return sum;
}

void dfs1(int x) {
    if (volt[x]) return;
    volt[x] = true;
    ans += cnt[(k - wsum % k) % k];
    for (edge e : g[x]) {
        wsum += e.w;
        dfs1(e.to);
        wsum -= e.w;
    }
    volt[x] = false;
}

void dfs2(int x) {
    if (volt[x]) return;
    volt[x] = true;
    cnt[wsum % k]++;
    for (edge e : g[x]) {
        wsum += e.w;
        dfs2(e.to);
        wsum -= e.w;
    }
    volt[x] = false;
}

void solve(int x) {
    if (volt[x]) return;
    sz = get_c(x);
    get_c(x);
    volt[c] = true;
    fill(cnt.begin(), cnt.end(), 0);
    cnt[0] = 1;
    for (edge e : g[c]) {
        wsum = e.w;
        dfs1(e.to);
        dfs2(e.to);
    }
    int C = c;
    for (edge e : g[C]) solve(e.to);
}

int main()
{
    cin >> n >> k;
    int a, b, W;
    for (int i = 0; i < n - 1; i++) {
        cin >> a >> b >> W;
        g[a].push_back(edge(b, W));
        g[b].push_back(edge(a, W));
    }
    solve(1);
    cout << ans;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms3920 KiB
2Accepted3ms4260 KiB
subtask215/15
3Accepted3ms4392 KiB
4Accepted3ms4456 KiB
5Accepted4ms4348 KiB
6Accepted4ms4600 KiB
7Accepted4ms4556 KiB
8Accepted4ms4864 KiB
9Accepted4ms4812 KiB
subtask315/15
10Accepted39ms5656 KiB
11Accepted10ms5652 KiB
12Accepted171ms8420 KiB
13Accepted155ms8420 KiB
14Accepted180ms8900 KiB
subtask420/20
15Accepted4ms5204 KiB
16Accepted4ms5368 KiB
17Accepted18ms6436 KiB
18Accepted68ms10328 KiB
19Accepted98ms12676 KiB
20Accepted137ms15616 KiB
21Accepted128ms15212 KiB
22Accepted156ms17196 KiB
subtask550/50
23Accepted158ms9656 KiB
24Accepted82ms8152 KiB
25Accepted114ms8580 KiB
26Accepted25ms6960 KiB
27Accepted82ms8256 KiB
28Accepted171ms9904 KiB
29Accepted159ms9844 KiB
30Accepted159ms9848 KiB
31Accepted180ms10272 KiB