1857G - Counting Graphs - CodeForces Solution


combinatorics divide and conquer dsu graphs greedy sortings

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define CaseT int CaseT; cin >> CaseT; while(CaseT--)
#define endl '\n'
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<PII, int> PPI;
typedef pair<PII, PII> PPP;

const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const double eps = 1e-6;
const ll p = 998244353;

int n;
ll s;
struct EDGE {
    ll a, b, w;
}edges[N];
bool vis[N];
int f[N];
ll siz[N];

void init() {
    memset(vis, false, sizeof(vis));
    for (int i = 1; i <= n; i++) {
        f[i] = i;
        siz[i] = 1;
    }
}

bool cmp(EDGE &a, EDGE &b) {
    return a.w < b.w;
}

int find(int x) {
    if (f[x] != x) return f[x] = find(f[x]);
    return f[x];
}

ll qmi(ll a, ll k) {
    ll res = 1;
    while (k) {
        if (k & 1) res = res * a % p;
        k >>= 1;
        a = a * a % p;
    }
    return res;
}

void solve() {
    cin >> n >> s;
    init();
    for (int i = 1; i <= n - 1; i++) {
        ll a, b, w;
        cin >> edges[i].a >> edges[i].b >> edges[i].w;
    }

    sort(edges + 1, edges + n, cmp);

    ll res = 1;
    for (int i = 1; i <= n - 1; i++) {
        ll a = edges[i].a;
        ll b = edges[i].b;
        ll w = edges[i].w;
        a = find(a);
        b = find(b);

        if (a == b) continue;
        if (w == s) break;
        res = res * qmi(s - w + 1, siz[a] * siz[b] - 1) % p;
        siz[b] += siz[a];
        f[a] = b;
    }

    cout << res << endl;
}

int main() {
    cin.tie(0), cout.tie(0)->sync_with_stdio(false);
    CaseT
    solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest
727C - Guess the Array
1625C - Road Optimization
1715D - 2+ doors
267A - Subtractions
1582A - Luntik and Concerts
560A - Currency System in Geraldion
946A - Partition
1068B - LCM
1692E - Binary Deque
679A - Bear and Prime 100
488A - Giga Tower
14A - Letter
1150A - Stock Arbitraging
1552A - Subsequence Permutation
1131F - Asya And Kittens
1475F - Unusual Matrix
133B - Unary
1547A - Shortest Path with Obstacle
624A - Save Luke
1238A - Prime Subtraction
1107C - Brutality
1391B - Fix You