rishu110067

unsatisfied barton

Feb 10th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4.  
  5. void print(priority_queue<pair<ll,ll>> p)
  6. {
  7. while(!p.empty())
  8. {
  9. cout<<p.top().first<<" -> "<<p.top().second<<endl;
  10. p.pop();
  11. }
  12. }
  13.  
  14. ll like(vector<ll> a)
  15. {
  16.  
  17. priority_queue<pair<ll,ll>> p;
  18. ll count=0; ll num=-1;
  19. for(ll i=0;i<a.size()-1;i++)
  20. {
  21. if(a[i]==a[i+1])
  22. { count++; num=a[i];}
  23. else
  24. {
  25. if(count!=0) p.push(make_pair(count,num));
  26. count=0; num=-1;
  27. }
  28. }
  29. if(count!=0)
  30. p.push(make_pair(count,num));
  31.  
  32. //print(p);
  33.  
  34. pair<ll,ll> x,y;
  35. priority_queue<pair<ll,ll>> q;
  36. ll sum=0;
  37. while(p.size()>=2)
  38. {
  39. x = p.top(); p.pop();
  40. y = p.top(); p.pop();
  41. if(x.second!=y.second)
  42. {
  43. if(x.first > y.first)
  44. { sum+=y.first; x.first-=y.first; p.push(x); }
  45. else if(y.first > x.first)
  46. { sum+=x.first; y.first-=x.first; p.push(y); }
  47. else
  48. { sum+=x.first; }
  49. }
  50. else
  51. {
  52. p.push(y);
  53. if(q.empty() || q.top().second==x.second) q.push(x);
  54. else
  55. {
  56. y=q.top(); q.pop();
  57. if(x.first > y.first)
  58. { sum+=y.first; x.first-=y.first; p.push(x); }
  59. else if(y.first > x.first)
  60. { sum+=x.first; y.first-=x.first; p.push(y); }
  61. else
  62. { sum+=x.first; }
  63. }
  64. }
  65. }
  66. if(p.size()==1)
  67. {
  68. if(q.empty() || p.top().second==q.top().second) { sum+=p.top().first; p.pop(); }
  69. else
  70. {
  71. x=p.top(); p.pop();
  72. y=q.top(); q.pop();
  73. if(x.first > y.first)
  74. { sum+=y.first; x.first-=y.first; q.push(x); }
  75. else if(y.first > x.first)
  76. { sum+=x.first; y.first-=x.first; q.push(y); }
  77. else
  78. { sum+=x.first; }
  79. }
  80. }
  81. while(!q.empty())
  82. {
  83. sum+=q.top().first; q.pop();
  84. }
  85.  
  86. return sum;
  87. }
  88.  
  89. bool impossible(vector<ll> a)
  90. {
  91. sort(a.begin(),a.end());
  92. ll n=a.size();
  93.  
  94. ll count=0; ll mx=0;
  95. for(ll i=0;i<n-1;i++)
  96. {
  97. if(a[i]==a[i+1]) count++;
  98. else count=0;
  99.  
  100. if(count>mx) mx=count;
  101. }
  102.  
  103. mx++;
  104. if(n%2==0 && mx>n/2) return true;
  105.  
  106. if(n%2==1 && mx > n/2 +1) return true;
  107.  
  108. return false;
  109. }
  110.  
  111. int main()
  112. {
  113. ios_base::sync_with_stdio(0);
  114. cout.tie(0); cin.tie(0);
  115.  
  116. ll n; cin>>n;
  117. vector<ll> a(n);
  118. for(ll i=0;i<n;i++) cin>>a[i];
  119.  
  120. if(impossible(a))
  121. {cout<<-1<<endl; return 0;}
  122.  
  123. cout<<like(a)<<endl;
  124. }
Add Comment
Please, Sign In to add comment