• Source
    1. #include<bits/stdc++.h>
    2.  
    3. using namespace std;
    4.  
    5. int par[505];
    6.  
    7. int khoj_rep(int r)
    8. {
    9. if(par[r]==r)
    10. {
    11. return r;
    12. }
    13. else
    14. {
    15. return par[r] = khoj_rep(par[r]);
    16. }
    17. }
    18.  
    19. struct data
    20. {
    21. int a,b,c,d;
    22. }store[505];
    23.  
    24. struct data1
    25. {
    26. int u,v,cost;
    27. }arr[250000];
    28.  
    29. bool cmp(data1 lhs,data1 rhs)
    30. {
    31. return lhs.cost<rhs.cost;
    32. }
    33.  
    34. int main()
    35. {
    36. long test,n,i,j,k,cnt,cnt1,counter,rolls,tmp,tmp1,tmp2,u,v,sub,tag;
    37. char a,b,c,d;
    38. cin>>test;
    39. while(test--)
    40. {
    41. cin>>n;
    42. store[0].a=0;
    43. store[0].b=0;
    44. store[0].c=0;
    45. store[0].d=0;
    46. for(i=1;i<=n;i++)
    47. {
    48. cin>>a>>b>>c>>d;
    49. store[i].a=a-48;
    50. store[i].b=b-48;
    51. store[i].c=c-48;
    52. store[i].d=d-48;
    53. }
    54.  
    55. for(i=0;i<=n;i++)
    56. {
    57. par[i]=i;
    58. }
    59.  
    60. k=0;
    61.  
    62. for(i=0;i<=n;i++)
    63. {
    64. cnt=0;
    65. for(j=i+1;j<=n;j++)
    66. {
    67. tmp=max(store[i].a,store[j].a);
    68. tmp2=min(store[i].a,store[j].a);
    69. tmp1=abs(store[i].a-store[j].a);
    70. sub=10-tmp+tmp2;
    71. cnt1=min(tmp1,sub);
    72. cnt+=cnt1;
    73.  
    74. tmp=max(store[i].b,store[j].b);
    75. tmp2=min(store[i].b,store[j].b);
    76. tmp1=abs(store[i].b-store[j].b);
    77. sub=10-tmp+tmp2;
    78. cnt1=min(tmp1,sub);
    79. cnt+=cnt1;
    80.  
    81. tmp=max(store[i].c,store[j].c);
    82. tmp2=min(store[i].c,store[j].c);
    83. tmp1=abs(store[i].c-store[j].c);
    84. sub=10-tmp+tmp2;
    85. cnt1=min(tmp1,sub);
    86. cnt+=cnt1;
    87.  
    88. tmp=max(store[i].d,store[j].d);
    89. tmp2=min(store[i].d,store[j].d);
    90. tmp1=abs(store[i].d-store[j].d);
    91. sub=10-tmp+tmp2;
    92. cnt1=min(tmp1,sub);
    93. cnt+=cnt1;
    94.  
    95. arr[k].u=i;
    96. arr[k].v=j;
    97. arr[k].cost=cnt;
    98. k++;
    99. cnt=0;
    100. }
    101. }
    102.  
    103. sort(arr,arr+k,cmp);
    104. counter=0;
    105. rolls=0;
    106. tag=0;
    107.  
    108. for(i=0;i<k;i++)
    109. {
    110. u=khoj_rep(arr[i].u);
    111. v=khoj_rep(arr[i].v);
    112. if(u!=v && tag==0)
    113. {
    114. par[u]=v;
    115. rolls+=arr[i].cost;
    116. if(arr[i].u==0)
    117. {
    118. tag=1;
    119. }
    120. }
    121.  
    122. else if(u!=v && arr[i].u>0)
    123. {
    124. par[u]=v;
    125. rolls+=arr[i].cost;
    126. counter++;
    127. if(counter==n)
    128. {
    129. break;
    130. }
    131. }
    132. }
    133. cout<<rolls<<endl;
    134. memset(par,0,sizeof(par));
    135. }
    136. return 0;
    137. }
    138.