fork download
  1. #include <algorithm>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <vector>
  5. #include <set>
  6. #include <numeric>
  7. #include <map>
  8. #include <unordered_map>
  9. using namespace std;
  10. #define all(a) a.begin(), a.end()
  11. #define ll long long
  12. #define fo(i,n) for (long long i = 0; i < n; i++)
  13. bool comp(pair<char,ll> a, pair<char,ll> b)
  14. {
  15. return (a.first < b.first);
  16. }
  17. bool comp2(pair<char,ll> a, pair<char,ll> b)
  18. {
  19. return (a.first > b.first);
  20. }
  21. int main()
  22. {
  23. ios_base::sync_with_stdio(false);
  24. cin.tie(0); cout.tie(0);
  25. ll n,m,i;
  26. ll a,b;
  27. string input;
  28. cin >> i;
  29. while (i--)
  30. {
  31. cin >> n >> m;
  32. ll res = 0;
  33. map<ll,ll> freq;
  34. vector<vector<ll>> nums(n,vector<ll>(m,0));
  35. set<ll> num;
  36. fo(j,n)
  37. {
  38. fo(k,m)
  39. {
  40. cin >> a;
  41. nums[j][k] = a;
  42. num.insert(a);
  43. if (j > 0)
  44. {
  45. if (nums[j-1][k] == a)
  46. {
  47. freq[a]++;
  48. }
  49. }
  50. if (k > 0)
  51. {
  52. if (nums[j][k-1] == a)
  53. {
  54. freq[a]++;
  55. }
  56. }
  57. }
  58. }
  59. ll maxi = 0;
  60. for (auto k : num)
  61. {
  62. if (freq[k] > maxi)
  63. {
  64. maxi = freq[k];
  65. if (maxi > 1)
  66. {
  67. maxi = 1;
  68. }
  69. }
  70. }
  71. for (auto k : num)
  72. {
  73. ll bruh = 2;
  74. res+= min(freq[k]+1,bruh);
  75. }
  76. cout << res-(maxi+1) << '\n';
  77. }
  78. }
Success #stdin #stdout 0s 5284KB
stdin
1
3 3
1 1 1
2 2 2
3 3 3
stdout
4