main.cc 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <algorithm>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <set>
  5. using namespace std;
  6. #define N_MAX 100000
  7. struct UF {
  8. int id[N_MAX + 1];
  9. int sz[N_MAX + 1];
  10. int n;
  11. void Init(int n) {
  12. memset(sz, 0, sizeof(sz));
  13. for (int i = 0; i <= n; i++) id[i] = i;
  14. }
  15. int Find(int i) {
  16. int j = id[i];
  17. if (i == j) return i;
  18. j = Find(j);
  19. id[i] = j;
  20. return j;
  21. }
  22. bool Union(int i, int j) {
  23. i = Find(i);
  24. j = Find(j);
  25. if (i == j) return false;
  26. if (sz[i] < sz[j]) {
  27. id[i] = j;
  28. } else {
  29. if (sz[i] == sz[j]) sz[i]++;
  30. id[j] = i;
  31. }
  32. return true;
  33. };
  34. } uf;
  35. struct Pair {
  36. int x;
  37. int y;
  38. bool operator<(const Pair &that) const {
  39. if (this->x != that.x) return this->x < that.x;
  40. return this->y < that.y;
  41. };
  42. };
  43. int main() {
  44. int T;
  45. scanf("%d", &T);
  46. for (int t = 1; t <= T; t++) {
  47. int N, M;
  48. scanf("%d %d", &N, &M);
  49. uf.Init(N);
  50. set<Pair> black;
  51. for (int i = 0, C, D; i < M; i++) {
  52. scanf("%d %d", &C, &D);
  53. if (C < D) black.insert(Pair{C, D});
  54. else black.insert(Pair{D, C});
  55. }
  56. int sugar = 0;
  57. set<Pair>::iterator it;
  58. for (it = black.begin(); it != black.end(); ++it)
  59. if (uf.Union(it->x, it->y)) sugar++;
  60. for (int i = 1; i < N; i++)
  61. for (int j = i + 1; j <= N; j++)
  62. if (uf.Union(i, j)) sugar += 2;
  63. printf("Case #%d: %d\n", t, sugar);
  64. }
  65. return 0;
  66. }