| # | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 | 
|---|---|---|---|---|---|---|---|
| 1121410 | namprozz | 경주 (Race) (IOI11_race) | C++17 | 0 ms | 0 KiB | 
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN = 200005;
int n;
ll k;
vector<pair<int, ll>> adj[MAXN];
int child[MAXN];
bool marked[MAXN];
void countChild(int u, int p)
{
    child[u] = 1;
    for(auto [v, w] : adj[u])
    {
        if(v == p or marked[v])
            continue;
        countChild(v, u);
        child[u] += child[v];
    }
}
int findCentroid(int u, int p, int n)
{
    for(auto [v, w] : adj[u])
    {
        if(v == p or marked[v])
            continue;
        if(child[v] > n / 2)
        {
            return findCentroid(v, u, n);
        }
    }
    return u;
}
unordered_map<ll, ll> dp;
void dfs(int u, int p, ll tong)
{
    if(tong > k)
        return;
    dp[tong]++;
    for(auto [v, w] : adj[u])
    {
        if(v == p or marked[v])
            continue;
        dfs(v, u, tong + w);
    }
}
ll res = 0;
void decomp(int u)
{
    countChild(u, -1);
    int c = findCentroid(u, -1, child[u]);
    marked[c] = true;
    dp.clear();
    dfs(c, -1, 0);
    for(auto [tong, dem] : dp)
    {
        if(dp.count(k - tong))
        {
            res += dem * dp[k - tong];
        }
    }
    for(auto [v, w] : adj[c])
    {
        if(marked[v])
            continue;
        decomp(v);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> k;
    for(int i = 0; i < n - 1; i++)
    {
        int u, v;
        ll w;
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    fill(marked, marked + n, false);
    decomp(0);
    if(res == 0)
    {
        cout << -1 << '\n';
    }
    else
    {
        cout << res << '\n';
    }
}
