• Source
    1. #include<bits/stdc++.h>
    2.  
    3. using namespace std;
    4.  
    5. long par[100005];
    6.  
    7. struct data
    8. {
    9. long u,v;
    10.  
    11. } arr[100005];
    12.  
    13. long khoj_rep(long r)
    14. {
    15. if(par[r]==r)
    16. {
    17. return r;
    18. }
    19. else
    20. {
    21. return par[r]=khoj_rep(par[r]);
    22. }
    23. }
    24.  
    25. int main()
    26. {
    27. long a,b,max1,max2,i,k,counter,u,v;
    28. while(cin>>a)
    29. {
    30. k=0;
    31. max2=0;
    32. while(a!=-1)
    33. {
    34. cin>>b;
    35.  
    36. arr[k].u=a;
    37. arr[k++].v=b;
    38.  
    39. max1=max(a,b);
    40. max2=max(max1,max2);
    41. cin>>a;
    42. }
    43.  
    44. for(i=1; i<=max2; i++)
    45. {
    46. par[i]=i;
    47. }
    48.  
    49. counter=0;
    50.  
    51. for(i=0; i<k; i++)
    52. {
    53. u=khoj_rep(arr[i].u);
    54. v=khoj_rep(arr[i].v);
    55. if(u!=v)
    56. {
    57. par[u]=v;
    58. }
    59. else if(u==v)
    60. {
    61. counter++;
    62. }
    63.  
    64. }
    65. cout<<counter<<endl;
    66. }
    67. return 0;
    68. }
    69.