poj 1182 并查集

  1. #include <stdio.h>
  2. int father[50050];
  3. void initializtion(int n)
  4. {
  5. for(int i=0; i<=n+1; i++)
  6. father[i] = i;
  7. }
  8. bool find(int a, int b)
  9. {
  10. //int flag = 0;
  11. if(a==b) return 0;
  12. else
  13. {
  14. int temp = a;
  15. if(temp == a && father[temp] == b)
  16. return 0;
  17. while(father[temp] != temp)
  18. {
  19. temp = father[temp];
  20. if(temp == b) return 1;
  21. if(temp == a) return 1;
  22. }
  23. return 0;
  24. }
  25. }
  26. void update(int a, int b)
  27. {
  28. int i = a;
  29. if(i == a && father[i] == b)
  30. return ;
  31. while(father[i] != i)
  32. {
  33. i = father[i];
  34. }
  35. father[i] = b;
  36. }
  37. int main()
  38. {
  39. int N, K;
  40. while(scanf("%d%d", &N, &K)!=EOF)
  41. {
  42. initializtion(N);
  43. int mistake = 0;
  44. int a, b, c;
  45. for(int i=0; i<K; i++)
  46. {
  47. scanf("%d%d%d", &a, &b, &c);
  48. if(b>N || c>N)
  49. {mistake++; continue;}
  50. if(a==1)
  51. {
  52. if(find(b, c) ) mistake ++;
  53. }
  54. if(a==2)
  55. {
  56. if(b==c) mistake++;
  57. else
  58. {
  59. if(find(b, c) ) mistake++;
  60. else update(b, c);
  61. }
  62. }
  63. }
  64. printf("%d\n", mistake);
  65. }
  66. return 0;
  67. }





附件列表

     

    posted @ 2015-01-29 11:41  sober_reflection  阅读(117)  评论(0编辑  收藏  举报