1776F - Train Splitting - CodeForces Solution


constructive algorithms graphs greedy *1700

Please click on ads to support us..

C++ Code:

#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';

template<class t, class u> bool pmin(t &a, u b) {if (b < a) {a = b; return true;} else return false;}
template<class t, class u> bool pmax(t &a, u b) {if (a < b) {a = b; return true;} else return false;}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int __ = 1;
    cin >> __;
    while (__--) {
        int n, m;
        cin >> n >> m;
        vector<vector<pair<int, int> > > g(n);
        int grid[n][n] = {};
        for (int i = 0; i < m; i++) {
            int u, v;
            cin >> u >> v;
            --u, --v;
            grid[u][v] = i + 1;
            grid[v][u] = i + 1;
            g[u].push_back({v, i + 1});
            g[v].push_back({u, i + 1});
        }
        if (n == 3) {
            if (m == 2) {
                cout << 2 << nl << 1 << " " << 2 << nl;
            }
            else {
                cout << 3 << nl << 1 << " " << 2 << " " << 3 << nl;
            }
            continue;
        }
        vector<int> ans(m + 1);
        int num;
        if (m == n * (n - 1) / 2) {
            num = 3;
            ans[grid[0][1]] = 1;
            ans[grid[0][n - 1]] = 1;
            for (int i = 2; i < n - 1; i++) {
                ans[grid[0][i]] = 3;
            }
        }
        else {
            num = 2;
            int node = 0;
            for (; node < n - 1; node++) {
                if (sz(g[node]) < n - 1) {
                    break;
                }
            }
            for (auto &v : g[node]) {
                ans[v.ss] = 1;
            }
        }
        cout << num << nl;
        for (int i = 1; i <= m; i++) {
            if (ans[i] == 0) {
                ans[i] = 2;
            }
            cout << ans[i] << " ";
        }
        cout << nl;
    }
}


Comments

Submit
0 Comments
More Questions

1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle