Description
小Y:“小R 你是萝莉控吗。”小R:“…”
为了避免这个尴尬的话题,小R 决定给小Y 做一道题。
有一个长度为n 的正整数数组A,满足Ai >= Ai+1,现在构造一个数组B,令Bi =。
现在,有一个n * n 的网格图,左下角坐标是(1, 1),右上角坐标是(n, n)。有一个小SB正在坐标为(n, 1) 的位置,每一时刻,如果他现在在(x, y),他可以选择走到(x ?-1,y + 1) 或者(x, (y + 1) div 2),如果选择后者,他要支付Bx的代价。
现在他想走到(1, 1),你可以告诉他他支付的代价最少是多少吗?注意在任何时候他都不能离开这个网格图。
Input
第一行输入一个正整数T 表示数据组数。
对于每组数据,第一行是一个整数n,接下来一行n 个整数表示数组A。
Output
对于每组数据,输出一个整数表示答案。
Sample Input
1
3
1 1 1
Sample Output
5
样例解释:
选择的路径可以是:(3, 1)->(2, 2)->(2, 1)->(1, 2)->(1, 1)
Data Constraint
对于30% 的数据,n <= 10
对于50% 的数据,n <=1000
对于100% 的数据,n<= 105,1 <= T<= 10,1 <= Ai<= 104
思路
合并果子
为什么?感性理解
每次往左走相当于合并两堆果子
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const ll inf=0x7fffffff,maxn=1e5+777;
ll c[maxn*2],n,ass=0,cnt=0,t=0;
void up(int x)
{
int i=x;
while(i/2>0)
{
if(c[i]<c[i/2]) swap(c[i],c[i/2]);else break;
i>>=1;
}
}
void down(int x)
{
int i=x;
while(i*2<=cnt)
{
int t=i*2;
if(t+1<=cnt&&c[t]>c[t+1]) t++;
if(c[i]>c[t]) swap(c[i],c[t]);else break;
i=t;
}
}
void ins(int x)
{
c[++cnt]=x;
up(cnt);
}
void del()
{
swap(c[1],c[cnt]);
cnt--;
down(1);
}
int pop()
{
int x=c[1]; del();
return x;
}
int main()
{
scanf("%d",&t);
while(t--)
{
memset(c,0,sizeof(c)); cnt=0; ass=0;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
ll x;
scanf("%lld",&x);
ins(x);
}
while(cnt>1)
{
int x1=pop(),x2=pop();
ass+=x1+x2;
ins(x1+x2);
}
printf("%lld\n",ass);
}
}