【CodeForces】500C New Year Book Reading

传送门

题目描述

output
standard output

New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.

As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.

  1. He lifts all the books above book x.
  2. He pushes book x out of the stack.
  3. He puts down the lifted books without changing their order.
  4. After reading book x, he puts book x on the top of the stack.

He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.

After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

解题思路

代码

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int n,m,cnt=0,temp,ans[505],w[505],b[1005],h[505];
 5 bool vis[1005];
 6 inline void read(int &x){
 7     x=0; register char ch=getchar();
 8     while(ch<'0'||ch>'9')ch=getchar();
 9     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
10 }
11 int main(){
12     read(n),read(m);
13     for(register int i=1;i<=n;i++)read(w[i]);
14     for(register int i=1;i<=m;i++){
15         read(temp),b[i]=temp;
16         if(!vis[temp])vis[temp]=1,ans[++cnt]=temp;
17     }
18     for(register int i=1;i<=n;i++){
19         h[ans[i]]=n-i+1;
20     }
21     long long ans=0;
22     for(register int i=1;i<=m;i++){
23         int nowh=h[b[i]]; h[b[i]]=n;
24         for(register int j=1;j<=n;j++){
25             if(h[j]>nowh&&b[i]!=j){
26                 h[j]--;
27                 ans+=w[j];
28             }
29         }
30     }
31     cout<<ans<<endl;
32 }

猜你喜欢

转载自www.cnblogs.com/Fang-Hao/p/9097425.html