1833G - Ksyusha and Chinchilla - CodeForces Solution


dfs and similar dp dsu greedy implementation trees

Please click on ads to support us..

C++ Code:

// trust the process
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(v) begin(v), end(v)
#define ff first
#define ss second
#define sz(x) ((int)x.size())

const char nl = '\n';
const int inf = 1e9 + 9;
const long long INF = 1e18 + 18;
const int N = 2e5 + 5;

vector<int> g[N];
vector<int> ans;
map<int, map<int, int> > mp;

int dfs(int u, int p) {
    int cur = 1;
    for (int v : g[u]) {
        if (v == p) continue;
        cur += dfs(v, u);
    }
    if (cur == 3) {
        ans.push_back(mp[u][p]);
        return 0;
    }
    return cur;
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    int tt = 1;
    cin >> tt;
    while (tt--) {
        int n;
        cin >> n;

        mp.clear();
        mp.insert({0, {{-1, -1}}});
        for (int i = 0; i < n; i++) {
            g[i].clear();
        }

        for (int i = 0; i < n - 1; i++) {
            int u, v;
            cin >> u >> v;
            --u, --v;
            g[u].push_back(v);
            g[v].push_back(u);
            mp[u][v] = mp[v][u] = i + 1;
        }
        
        if (n % 3) {
            cout << "-1\n";
            continue;
        }

        ans.clear();
        dfs(0, -1);
        if ((int)ans.size() != n / 3) {
            cout << "-1\n";
            continue;
        }

        cout << n / 3 - 1 << nl;
        for (int i = 0; i < (int)ans.size() - 1; i++) {
            cout << ans[i] << " ";
        }
        cout << nl;
    }
}


Comments

Submit
0 Comments
More Questions

1455C - Ping-pong
1644C - Increase Subarray Sums
1433A - Boring Apartments
1428B - Belted Rooms
519B - A and B and Compilation Errors
1152B - Neko Performs Cat Furrier Transform
1411A - In-game Chat
119A - Epic Game
703A - Mishka and Game
1504C - Balance the Bits
988A - Diverse Team
1312B - Bogosort
1616B - Mirror in the String
1660C - Get an Even String
489B - BerSU Ball
977C - Less or Equal
1505C - Fibonacci Words
1660A - Vasya and Coins
1660E - Matrix and Shifts
1293B - JOE is on TV
1584A - Mathematical Addition
1660B - Vlad and Candies
1472C - Long Jumps
1293D - Aroma's Search
918A - Eleven
1237A - Balanced Rating Changes
1616A - Integer Diversity
1627B - Not Sitting
1663C - Pōja Verdon
1497A - Meximization