#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define plx pair<ll,int>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define vi vector<int>
#define vvi vector<vi>
#define pp pair<ll,int>
#define ub(x,i) upper_bound(all(x),i)-x.begin()
using namespace std;
const int mxn=1e5+5,inf=10001;
map<ll,int>mp;
vector<ll>v;
ll t[2*mxn]{0};
ll qr(int l,int r,int sz,ll rs=0){
for(l+=sz,r+=sz;l<r;l>>=1,r>>=1){
if(l&1)rs=__gcd(rs,t[l++]);
if(r&1)rs=__gcd(rs,t[--r]);
}return rs;
}
void upd(int i,int sz,ll amt){
i+=sz;t[i]=amt;
for(i>>=1;i;i>>=1)t[i]=__gcd(t[2*i],t[2*i+1]);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;cin>>n;
for(int i=0;i<n;i++){
ll x;cin>>x;v.pb(x);mp[x]++;
}sort(all(v));v.erase(unique(all(v)),v.end());m=v.size();
for(int i=0;i<m;i++)t[i+m]=v[i];
for(int i=m-1;i>0;i--)t[i]=__gcd(t[2*i],t[2*i+1]);
ll rs=t[1];priority_queue<pll>pq;
cout<<rs<<'\n';
for(int i=n-1;i>=1;i--){
if(!pq.empty()&&((!v.empty()&&pq.top().f>v.back())||(v.empty()))){
pll u=pq.top();pq.pop();
rs+=u.f;u.s--;
if(u.s!=0)pq.push(u);
cout<<rs<<'\n';
continue;
}
if(v.size()>1){
int ls=v.size();
ll x=qr(0,ls-2,m);
ll g1=__gcd(v[ls-2],x);
ll g2=__gcd(v[ls-1],x);
ll g3=__gcd(g1,g2);
if(g1+v[ls-1]<g2+v[ls-2])upd(ls-2,m,v[ls-1]),swap(v[ls-1],v[ls-2]),swap(g1,g2);
mp[v[ls-1]]--;
if(mp[v[ls-1]]!=0)pq.push({v[ls-1],mp[v[ls-1]]});
rs+=g1+v[ls-1]-g3;
v.pop_back();
}
else {
rs+=v.back();
mp[v.back()]--;
if(mp[v.back()]!=0)pq.push({v.back(),mp[v.back()]});
v.pop_back();
}cout<<rs<<'\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |