柯南准备去读n本书,标号为1~n,每本书的重量为wi.
柯南家太小啦,没办法放下一个书橱,于是就只好将这些书堆成一个垂直的堆,他现在想要读第x本书,他要这么做。
1.举起在x上面的所有的书
2.然后将x书从堆里面拿出来
3.将x上面的书不改变顺序地放回去
4.将x放到最上面
他决定在m天内读书,在第j天,他会读第bj (1 ≤ bj ≤ n)本书. 他取出书的方式就如同上面说的那样。
做了这样的计划之后,他突然发现作为一个一年级学生他举起想读的书上的书实在是太重了。所以他决定改变书堆的顺序(也就是初始的书是怎么堆的),从而减少总归抬起书的重量。
注意:他将x书抽出来的时候不算进抬起的重量。
Input
给你两个整数 n (2 ≤ n ≤ 500) 和 m (1 ≤ m ≤ 1000) — 书的个数和读书的天数
接下来一行有n个整数表示 w1, w2, ..., wn (1 ≤ wi ≤ 100) — 书的重量。
第三行有m个整数表示每一天看什么书 b1, b2, ..., bm (1 ≤ bj ≤ n) Note that he can read the same book more than once.
Output
他将书堆里面的书重新排列之后最少要举起多少重量呢?
Example
Input
3 5 1 2 3 1 3 2 3 1
Output
12
Hint
Here's a picture depicting the example. Each vertical column presents the stacked books.
#include"cstdio"
#include"iostream"
#include"cstring"
#include"algorithm"
using namespace std;
int main()
{
int n , m;
int xx[502];
int yy[1002];
int p[502];
while(cin>>n>>m)
{
for(int i = 1 ; i <= n ; i ++)
{
cin>>p[i];
}
int sum = 0;
for(int i = 0 ; i < m ; i ++)
{
cin>>yy[i];
int k = 0;
memset(xx,0,sizeof(xx));
for(int j = i-1 ; j >= 0 ; j --)
{
if(yy[j] == yy[i])
break;
if(yy[j] != yy[i] && xx[yy[j]] == 0)
{
k += p[yy[j]];
xx[yy[j]] = 1;
}
}
sum += k;
}
cout<<sum<<endl;
}
return 0;
}