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]; // adj[u]: danh sách các đỉnh kề với u
  15.  
  16. bool vis[N]; // vis[u]: đỉnh u đã được thăm hay chưa
  17.  
  18. void dfs(int u) {
  19. vis[u] = true;
  20.  
  21. for (int v : adj[u]) {
  22. if (!vis[v]) dfs(v);
  23. }
  24. }
  25.  
  26. int main() {
  27. ios::sync_with_stdio(false);
  28. cin.tie(nullptr);
  29. cin >> n >> m;
  30. for (int i = 0; i < m; i++) {
  31. int u, v;
  32. cin >> u >> v;
  33. adj[u].push_back(v);
  34. adj[v].push_back(u);
  35. }
  36.  
  37. int num_cc = 0; // Số thành phần liên thông
  38. for (int u = 1; u <= n; u++) {
  39. if (!vis[u]) {
  40. num_cc++;
  41. dfs(u);
  42. }
  43. }
  44.  
  45. int ans = m - n + num_cc; // Số chu trình
  46.  
  47. cout << ans << '\n';
  48. }
Success #stdin #stdout 0.01s 5280KB
stdin
5 6
1 2
2 4
4 5
3 5
1 3
2 3
stdout
2