题解:P16279 「MierOI R1」Future
Yuhaochen666 · · 题解
题目传送门
蒟蒻写了一个手写堆供大家参考(观赏)。
思路
从前往后依次处理每一位,用一个大根堆(优先队列)存储之前所有的个位数字。
如果当前位是奇数位,则令
复杂度
正确性证明
因为每一个数字都只能放在十位或个位,而越大的数字放在十位一定更优,所以我们在处理每一位时都把之前最大的个位数字拿出来当十位数字,一定是最优的。
代码
#include <bits/stdc++.h>
using namespace std;
int a[100100];
int T,n,sum,cnt;
string s;
void cr(int m)//手写堆
{
int n=m/2;
while((n!=0)&&(a[n]<a[m]))
{
swap(a[n],a[m]);
m=n;
n/=2;
}
return;
}
void sc(int b)
{
int c=b,x=1;
while(x*2<=c)
{
if(x*2+1<=c)
{
if(max(a[x*2],a[x*2+1])<a[x])
{
break;
}
if(a[x*2+1]>a[x*2])
{
swap(a[x],a[x*2+1]);
x=x*2+1;
}
else
{
swap(a[x],a[x*2]);
x*=2;
}
}
else
{
if(a[x*2]>a[x])
{
swap(a[x],a[x*2]);
}
break;
}
}
return;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>T;
for(int i=1;i<=T;i++)
{
cin>>n;
cin>>s;
sum=0;
cnt=0;
a[1]=0;
for(int j=1;j<=n;j++)
{
if(j%2==1)//奇数位,sum 为当前留出一个最大的个位数字的得分
{
if((s[j-1]-'0')<a[1])//当前位比堆顶小,将堆顶留出
{
sum=sum-a[1]+(s[j-1]-'0');
}
cnt++;
a[cnt]=(s[j-1]-'0');
cr(cnt);
}
else//偶数位,sum 为当前得分
{
sum=sum+a[1]*10+(s[j-1]-'0');//取堆顶当十位数字
a[1]=(s[j-1]-'0');
sc(cnt);//把个位数字插入堆中
}
}
cout<<sum<<'\n';
}
return 0;
}