fork(1) download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int find(vector<int>& d, int a) {
  6. if(d[a] < 0) return a;
  7. return d[a] = find(d, d[a]);
  8. }
  9.  
  10. void join(vector<int>& d, int a, int b) {
  11. a = find(d, a);
  12. b = find(d, b);
  13. if(a == b) return;
  14. d[a] += d[b];
  15. d[b] = a;
  16. }
  17.  
  18. int main() {
  19. int n, m;
  20. cin >> n >> m;
  21.  
  22. vector<vector<int>> adj(n);
  23. vector<int> d(n, -1);
  24. vector<pair<int,int>> edges;
  25.  
  26. for(int i = 0; i < m; i++) {
  27. int n1, n2;
  28. cin >> n1 >> n2;
  29. n1--; n2--;
  30.  
  31. adj[n1].push_back(n2);
  32. adj[n2].push_back(n1);
  33. edges.push_back({n1,n2});
  34. }
  35.  
  36. for(int i = 0; i < n; i++) {
  37. for(int j = 1; j < adj[i].size(); j++) {
  38. join(d, adj[i][j-1], adj[i][j]);
  39. }
  40. }
  41.  
  42. bool odd = false;
  43. for(int i = 0; i < n; i++) {
  44. if(d[i] < 0) {
  45. for(auto j : adj[i]) {
  46. if(find(d,i) == find(d,j)) {
  47. odd = true;
  48. }
  49. }
  50. }
  51. }
  52.  
  53. for(auto i : edges) {
  54. join(d,i.first,i.second);
  55. }
  56.  
  57. int components = 0;
  58. for(int i = 0; i < n; i++) {
  59. if(d[i] < 0) components++;
  60. }
  61.  
  62. components--;
  63. if(!odd) components++;
  64.  
  65. cout << components << endl;
  66. }
Success #stdin #stdout 0s 4176KB
stdin
5 10
1 2
2 3
3 4
4 5
5 1
1 3
2 4
3 5
4 1
5 2
stdout
0