Advertisement
a53

conexidad

a53
Mar 14th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. #include <cstdio>
  2. #include <algorithm>
  3. #include <numeric>
  4. #include <memory>
  5. using namespace std;
  6.  
  7. using file_pointer = unique_ptr<FILE, decltype(&fclose)>;
  8.  
  9. enum { OUTSIDE_COMPONENT, IN_COMPONENT };
  10.  
  11. int p[100], extra[100];
  12. int N, M;
  13.  
  14. int root(int node) {
  15. while (node != p[node]) node = p[node];
  16. return node;
  17. }
  18.  
  19. void join(int x, int y) {
  20. x = root(x); y = root(y);
  21. if (x == y) return;
  22. p[x] = y;
  23. }
  24.  
  25. void solve(file_pointer& f) {
  26. int node[2] = {-1, -1};
  27. for (int lap: {OUTSIDE_COMPONENT, IN_COMPONENT}) {
  28. for (int i = 0; i < N; ++i) {
  29. if ((root(i) == root(0)) == lap
  30. && (node[lap] == -1 || extra[node[lap]] > extra[i])) {
  31. node[lap] = i;
  32. }
  33. }
  34. }
  35.  
  36. if (node[0] == -1 || node[1] == -1) {
  37. fprintf(f.get(), "%d\n%d\n", *max_element(extra, extra + N),
  38. accumulate(extra, extra + N, 0) / 2);
  39. } else {
  40. join(node[0], node[1]);
  41. ++extra[node[0]]; ++extra[node[1]];
  42. solve(f);
  43. fprintf(f.get(), "%d %d\n", node[0] + 1, node[1] + 1);
  44. }
  45. }
  46.  
  47. int main() {
  48. file_pointer f(fopen("conexidad.in", "r"), &fclose);
  49. fscanf(f.get(), "%d%d", &N, &M);
  50. iota(p, p + N, 0);
  51. for (int _ = 0; _ < M; ++_) {
  52. int x, y; fscanf(f.get(), "%d%d", &x, &y); --x; --y;
  53. join(x, y);
  54. }
  55.  
  56. f.reset(fopen("conexidad.out", "w"));
  57. solve(f);
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement