fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 2e3 + 5;
  12.  
  13. int n, m;
  14. vector<int> adj[N];
  15.  
  16. int tin[N], low[N], timer;
  17. int id[N];
  18. vector<int> st;
  19. bool in_stack[N];
  20.  
  21. void dfs(int u) {
  22. tin[u] = low[u] = ++timer;
  23. st.push_back(u);
  24. in_stack[u] = true;
  25.  
  26. for (int v : adj[u]) {
  27. if (!tin[v]) {
  28. dfs(v);
  29. }
  30. if (in_stack[v]) {
  31. low[u] = min(low[u], low[v]);
  32. }
  33. }
  34.  
  35. if (low[u] == tin[u]) {
  36. while (true) {
  37. int v = st.back(); st.pop_back();
  38. in_stack[v] = false;
  39. id[v] = u;
  40. if (v == u) break;
  41. }
  42. }
  43. }
  44.  
  45. int indeg[N];
  46. int outdeg[N];
  47.  
  48. int main() {
  49. ios::sync_with_stdio(false);
  50. cin.tie(nullptr);
  51. cin >> n >> m;
  52.  
  53. for (int i = 0; i < m; i++) {
  54. int u, v;
  55. cin >> u >> v;
  56. adj[u].push_back(v);
  57. }
  58.  
  59. timer = 0;
  60. for (int u = 1; u <= n; u++) {
  61. if (!tin[u]) dfs(u);
  62. }
  63.  
  64. for (int u = 1; u <= n; u++) {
  65. for (int v : adj[u]) {
  66. if (id[u] == id[v]) continue;
  67. outdeg[id[u]]++;
  68. indeg[id[v]]++;
  69. }
  70. }
  71.  
  72. int cnt_s = 0, cnt_t = 0;
  73. int s = -1, t = -1;
  74.  
  75. for (int u = 1; u <= n; u++) {
  76. if (u != id[u]) continue;
  77. if (indeg[u] == 0) {
  78. cnt_s++;
  79. s = u;
  80. }
  81. if (outdeg[u] == 0) {
  82. cnt_t++;
  83. t = u;
  84. }
  85. }
  86.  
  87. if (cnt_s == 1 && cnt_t == 1) {
  88. cout << "YES" << '\n';
  89. cout << t << ' ' << s << '\n';
  90. }
  91. else {
  92. cout << "NO" << '\n';
  93. }
  94. }
  95.  
Success #stdin #stdout 0.01s 5284KB
stdin
3 2
1 2
2 3
stdout
YES
3 1