Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- void print(priority_queue<pair<ll,ll>> p)
- {
- while(!p.empty())
- {
- cout<<p.top().first<<" -> "<<p.top().second<<endl;
- p.pop();
- }
- }
- ll like(vector<ll> a)
- {
- priority_queue<pair<ll,ll>> p;
- ll count=0; ll num=-1;
- for(ll i=0;i<a.size()-1;i++)
- {
- if(a[i]==a[i+1])
- { count++; num=a[i];}
- else
- {
- if(count!=0) p.push(make_pair(count,num));
- count=0; num=-1;
- }
- }
- if(count!=0)
- p.push(make_pair(count,num));
- //print(p);
- pair<ll,ll> x,y;
- priority_queue<pair<ll,ll>> q;
- ll sum=0;
- while(p.size()>=2)
- {
- x = p.top(); p.pop();
- y = p.top(); p.pop();
- if(x.second!=y.second)
- {
- if(x.first > y.first)
- { sum+=y.first; x.first-=y.first; p.push(x); }
- else if(y.first > x.first)
- { sum+=x.first; y.first-=x.first; p.push(y); }
- else
- { sum+=x.first; }
- }
- else
- {
- p.push(y);
- if(q.empty() || q.top().second==x.second) q.push(x);
- else
- {
- y=q.top(); q.pop();
- if(x.first > y.first)
- { sum+=y.first; x.first-=y.first; p.push(x); }
- else if(y.first > x.first)
- { sum+=x.first; y.first-=x.first; p.push(y); }
- else
- { sum+=x.first; }
- }
- }
- }
- if(p.size()==1)
- {
- if(q.empty() || p.top().second==q.top().second) { sum+=p.top().first; p.pop(); }
- else
- {
- x=p.top(); p.pop();
- y=q.top(); q.pop();
- if(x.first > y.first)
- { sum+=y.first; x.first-=y.first; q.push(x); }
- else if(y.first > x.first)
- { sum+=x.first; y.first-=x.first; q.push(y); }
- else
- { sum+=x.first; }
- }
- }
- while(!q.empty())
- {
- sum+=q.top().first; q.pop();
- }
- return sum;
- }
- bool impossible(vector<ll> a)
- {
- sort(a.begin(),a.end());
- ll n=a.size();
- ll count=0; ll mx=0;
- for(ll i=0;i<n-1;i++)
- {
- if(a[i]==a[i+1]) count++;
- else count=0;
- if(count>mx) mx=count;
- }
- mx++;
- if(n%2==0 && mx>n/2) return true;
- if(n%2==1 && mx > n/2 +1) return true;
- return false;
- }
- int main()
- {
- ios_base::sync_with_stdio(0);
- cout.tie(0); cin.tie(0);
- ll n; cin>>n;
- vector<ll> a(n);
- for(ll i=0;i<n;i++) cin>>a[i];
- if(impossible(a))
- {cout<<-1<<endl; return 0;}
- cout<<like(a)<<endl;
- }
Add Comment
Please, Sign In to add comment