File size: 2,948 Bytes
1fd0050 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | #include <bits/stdc++.h>
using namespace std;
class FastScanner {
static constexpr size_t BUFSIZE = 1 << 20;
unsigned char buf[BUFSIZE];
size_t idx = 0, size = 0;
inline bool refill() {
size = fread(buf, 1, BUFSIZE, stdin);
idx = 0;
return size > 0;
}
public:
template <class T>
bool readInt(T &out) {
out = 0;
T sign = 1;
unsigned char c;
do {
if (idx >= size && !refill()) return false;
c = buf[idx++];
} while (c <= ' ');
if (c == '-') {
sign = -1;
if (idx >= size && !refill()) return false;
c = buf[idx++];
}
for (; c > ' '; ) {
out = out * 10 + (c - '0');
if (idx >= size) {
if (!refill()) break;
}
c = buf[idx++];
}
out *= sign;
return true;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
FastScanner fs;
int n, m;
if (!fs.readInt(n)) return 0;
fs.readInt(m);
// Read and ignore scoring parameters.
for (int i = 0; i < 10; i++) {
int x; fs.readInt(x);
}
vector<int> head(n + 1, -1), rhead(n + 1, -1);
vector<int> to(m), nxt(m), rto(m), rnxt(m);
vector<int> outdeg(n + 1, 0);
for (int i = 0; i < m; i++) {
int u, v;
fs.readInt(u); fs.readInt(v);
to[i] = v;
nxt[i] = head[u];
head[u] = i;
rto[i] = u;
rnxt[i] = rhead[v];
rhead[v] = i;
outdeg[u]++;
}
int start = 1;
for (int v = 2; v <= n; v++) {
if (outdeg[v] > outdeg[start]) start = v;
}
vector<char> vis(n + 1, 0);
vector<int> outPtr = head, inPtr = rhead;
deque<int> path;
path.push_back(start);
vis[start] = 1;
int first = start, last = start;
bool progress = true;
while (progress) {
progress = false;
// Extend forward
while (true) {
int &e = outPtr[last];
while (e != -1 && vis[to[e]]) e = nxt[e];
if (e == -1) break;
int nx = to[e];
e = nxt[e];
if (!vis[nx]) {
vis[nx] = 1;
path.push_back(nx);
last = nx;
progress = true;
}
}
// Extend backward
while (true) {
int &e = inPtr[first];
while (e != -1 && vis[rto[e]]) e = rnxt[e];
if (e == -1) break;
int pr = rto[e];
e = rnxt[e];
if (!vis[pr]) {
vis[pr] = 1;
path.push_front(pr);
first = pr;
progress = true;
}
}
}
cout << path.size() << "\n";
for (size_t i = 0; i < path.size(); i++) {
if (i) cout << ' ';
cout << path[i];
}
cout << "\n";
return 0;
} |