New Year Book Reading CF500C题解

· · 题解

原题链接:New Year Book Reading

题目大意

一个栈 S ,栈中存在 N 本书,从 S 中取 M 次书,每次取书 A 有 3 部分:

  1. 将栈中 A 以上的书拿走,设 i 为 A 之上的书,则花费的价值 sum 为:sum\eqcirc\sum w[i]
  2. 拿走 A ,并把之前被拿走的书原样放回(无花费)。
  3. 将 A 重新放回栈顶(无花费)。

最后的答案

ans\eqcirc\sum sum

已知 n , m ,数组 w ,和取书的操作数组 d ,求在栈的初始排列最合理时, ans 的最小值。

算法

我们用贪心的思路考虑。不妨设前后两本书先后为 a , b (且 a 第一次出现要比 b 第一次出现早)。

所以,对于 a,b 使得 a 第一次出现要比 b 第一次出现早,a 应该排在 b 的前面。

同时,因为任意两个数都要比对一次,造成的结果本质就是将其冒泡排序了一遍,所以直接排序即可。

用易于理解的话来说,就是按照第一次出现的顺序排序,来作为初始的栈。

对于没有在数组 d 中出现的书,将其放在栈的底部,忽视即可。

在初始栈算好之后,模拟即可。

代码

#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;
}

另

这道题是橙题。这道题是橙题?震惊!