fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdio>
  4. #include <iomanip>
  5. #include <sstream>
  6. #include <cstring>
  7. #include <string>
  8. #include <cmath>
  9. #include <stack>
  10. #include <list>
  11. #include <queue>
  12. #include <deque>
  13. #include <set>
  14. #include <map>
  15. #include <vector>
  16. #include <algorithm>
  17. #include <numeric>
  18. #include <utility>
  19. #include <functional>
  20. #include <limits>
  21. using namespace std;
  22.  
  23. typedef long long ll;
  24. typedef unsigned long long ull;
  25. typedef unsigned int ui;
  26. typedef pair<int,int> pii;
  27. typedef vector<vector<int> > graph;
  28.  
  29. const double pi = acos(-1.0);
  30.  
  31. #define oned(a, x1, x2) { cout << #a << ":"; for(int _i = (x1); _i < (x2); _i++){ cout << " " << a[_i]; } cout << endl; }
  32. #define twod(a, x1, x2, y1, y2) { cout << #a << ":" << endl; for(int _i = (x1); _i < (x2); _i++){ for(int _j = (y1); _j < (y2); _j++){ cout << (_j > y1 ? " " : "") << a[_i][_j]; } cout << endl; } }
  33.  
  34. #define mp make_pair
  35. #define pb push_back
  36. #define fst first
  37. #define snd second
  38.  
  39. #define MAXN 300005
  40.  
  41. int parent[MAXN];
  42.  
  43. int Group(int a) {
  44. if(parent[a]==a) {
  45. return a;
  46. } else {
  47. return parent[a] = Group(parent[a]);
  48. }
  49. }
  50.  
  51. int n, m, x[MAXN], y[MAXN];
  52.  
  53. int adj[MAXN];
  54.  
  55. void solve() {
  56. for(int i = 1; i <= n; i++) {
  57. parent[i] = i;
  58. }
  59.  
  60. memset(adj,0,sizeof(adj));
  61. for(int i = 1; i <= m; i++) {
  62. int a = Group(x[i]);
  63. int b = Group(y[i]);
  64. if(a==b) {
  65. cout << i << endl;
  66. return;
  67. } else {
  68. if(adj[a]) {
  69. parent[adj[a]] = b;
  70. }
  71. if(adj[b]) {
  72. parent[adj[b]] = a;
  73. }
  74. adj[a] = b;
  75. adj[b] = a;
  76. }
  77. }
  78. }
  79.  
  80. int main() {
  81. ios_base::sync_with_stdio(false);
  82. // freopen("input.in", "r", stdin);
  83. while(cin >> n >> m) {
  84. for(int i = 1; i <= m; i++) {
  85. cin >> x[i] >> y[i];
  86. }
  87. solve();
  88. }
  89. }
  90.  
Success #stdin #stdout 0s 8120KB
stdin
Standard input is empty
stdout
Standard output is empty