1217D - Coloring Edges - CodeForces Solution


constructive algorithms dfs and similar graphs *2100

Please click on ads to support us..

C++ Code:

/*
Problem: 1217D
Date: 02-03-2024 06:15 AM
*/


#include <bits/stdc++.h>

#define ll long long
using namespace std;

const int N = 5005;
int n, m, u[N], v[N];
vector<int> adj[N];
vector<int> topsort;
int pos[N];
bool visited[N];

void dfs(int u) {
    if(visited[u]) return;
    visited[u] = true;
    for(int v : adj[u]) {
        dfs(v);
    }
    topsort.push_back(u);
}

int main() {
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for(int i = 0; i < m; i++) {
        cin >> u[i] >> v[i];
        adj[u[i]].push_back(v[i]);
    }
    for(int i = 1; i <= n; i++) {
        dfs(i);
    }
    for(int i = 0; i < n; i++) {
        pos[topsort[i]] = i;
    }
    bool cycle = false;
    for(int i = 0; i < m; i++) {
        if(pos[u[i]] < pos[v[i]]) {
            cycle = true;
        }
    }
    if(!cycle) {
        cout << 1 << endl;
        for(int i = 0; i < m; i++) {
            cout << 1 << " ";
        }
        cout << endl;
    }else {
        cout << 2 << endl;
        for(int i = 0; i < m; i++) {
            cout << (u[i] < v[i] ? 1 : 2) << " ";
        }
        cout << endl;
    }
}


Comments

Submit
0 Comments
More Questions

1663C - Pōja Verdon
1497A - Meximization
1633B - Minority
688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays
540A - Combination Lock
1553C - Penalty
1474E - What Is It
1335B - Construct the String
1004B - Sonya and Exhibition
1397A - Juggling Letters
985C - Liebig's Barrels
115A - Party
746B - Decoding
1424G - Years
1663A - Who Tested
1073B - Vasya and Books
195B - After Training
455A - Boredom
1099A - Snowball
1651D - Nearest Excluded Points
599A - Patrick and Shopping
237A - Free Cash
1615B - And It's Non-Zero
1619E - MEX and Increments
34B - Sale
1436A - Reorder
1363C - Game On Leaves
1373C - Pluses and Minuses