This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define int long long
#define pb push_back
#define pii pair<int,int>
#define fr first
#define sc second
using namespace std;
const int N = 2e5+5;
const int M = 5e5+5;
vector<int> adj[N];
vector<int> opp[N];
vector<int> marker;
vector<int> par;
vector<int> keep;
vector<bool> vis;
bool dfs(int x) {
marker[x] = 1;
for (auto item : adj[x]) {
if (!marker[item]) {
par[item] = x;
if (dfs(item)) return true;
} else if (marker[item] == 1) return true;
}
marker[x] = 2;
return false;
}
signed main() {
int n, m; cin >> n >> m;
marker.assign(n+1, 0);
par.assign(n+1, -1);
vis.assign(n+1, 0);
vector<pii> v;
for (int i = 0; i < m; i++) {
int a, b; cin >> a >> b;
adj[b].pb(a);
opp[a].pb(b);
}
for (int i = 1; i <= n; i++) {
if (!marker[i]) {
if (dfs(i)) {
cout << -1 << endl;
return 0;
}
}
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
queue<int> q;
q.push(i);
while(!q.empty()) {
int cur = q.front(); q.pop();
vis[cur] = 1;
if (adj[cur].size() == 0) {
for (auto item : opp[cur]) {
if (!vis[item]) {
q.push(item);
v.pb({item, 0});
}
}
} else if (opp[cur].size() == 0) {
for (auto item : adj[cur]) {
if (!vis[item]) {
q.push(item);
v.pb({item, 1});
}
}
}
else {
bool pushed = false;
for (auto item : adj[cur]) {
if (!vis[item]) {
pushed = true;
q.push(item);
v.pb({item, 1});
}
}
if (pushed) {
for (auto item : opp[cur]) {
if (!vis[item]) {
q.push(item);
v.pb({item, 0});
}
}
} else {
bool pulled = false;
for (auto item : opp[cur]) {
if (!vis[item]) {
pulled = true;
q.push(item);
v.pb({item, 0});
}
}
if (pulled) {
for (auto item : adj[cur]) {
if (!vis[item]) {
q.push(item);
v.pb({item, 1});
}
}
}
}
}
}
}
}
cout << v.size() << endl;
for (auto item : v) cout << item.fr << " " << item.sc << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |