New Year Book Reading CF500C题解
watermouthhang · · 题解
原题链接:New Year Book Reading
题目大意
一个栈
- 将栈中
A 以上的书拿走,设i 为A 之上的书,则花费的价值sum 为:sum\eqcirc\sum w[i] - 拿走
A ,并把之前被拿走的书原样放回(无花费)。 - 将
A 重新放回栈顶(无花费)。
最后的答案
已知
算法
我们用贪心的思路考虑。不妨设前后两本书先后为
- 当
a 在b 前时,a 需要花费w[a]+q 的代价(q 为常数) - 当
a 在b 后时,a 需要花费w[a]+w[b]+q 的代价(q 为常数)
所以,对于
同时,因为任意两个数都要比对一次,造成的结果本质就是将其冒泡排序了一遍,所以直接排序即可。
用易于理解的话来说,就是按照第一次出现的顺序排序,来作为初始的栈。
对于没有在数组
在初始栈算好之后,模拟即可。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <iomanip>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
#include <cstdint>
//头文件部分不必在意
using namespace std;
int n,m;
int w[510],d[1010];//如题
int fst[510],top=0;//记录第一次出现的位置
bool tong[510];//辅助判断
int rtans()//返回答案
{
int ans=0;
for(int i=1;i<=m;++i)
{
int tmp=114514,sum=0;//喵~
for(int j=1;j<=top;++j)//传送带式移动
{
if(fst[j]==d[i])
{
if(j==1)//特判,防止bug
{
break;
}
fst[1]=fst[j];
fst[j]=tmp;
break;
}
else
{
sum+=w[fst[j]];
swap(tmp,fst[j]);
}
}
ans+=sum;
}
return ans;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
{
scanf("%d",&w[i]);
}
for(int i=1;i<=m;++i)
{
scanf("%d",&d[i]);
if(!tong[d[i]])
{
tong[d[i]]=1;
fst[++top]=d[i];
}//判断第一次出现的位置
}
printf("%d\n",rtans());//输出答案
return 0;
}
另
这道题是橙题。这道题是橙题?震惊!