题意:有n本书,每本书有重量,编号为1-n,m天,每天读一本书,n本书叠在一起,每次读书的时候要把要读的书上面的所有书搬开然后拿出要读的书放在最上面(如下图),问怎样堆书才能使得搬动的书的重量和最少,输出这个值
思路:贪心,按先要读的书的顺序来堆放,其实和书的重量没有关系,因为你要看一本书的话一定要把上面的书拿开,所以肯定尽量让它在前面
AC代码:
#include "iostream" #include "string.h" #include "stack" #include "queue" #include "string" #include "vector" #include "set" #include "map" #include "algorithm" #include "stdio.h" #include "math.h" #pragma comment(linker, "/STACK:102400000,102400000") #define ll long long #define endl (" ") #define bug(x) cout<<x<<" "<<"UUUUU"<<endl; #define mem(a,x) memset(a,x,sizeof(a)) #define mp(x,y) make_pair(x,y) #define pb(x) push_back(x) #define ft (frist) #define sd (second) #define lrt (rt<<1) #define rrt (rt<<1|1) using namespace std; const long long INF = 1e18+1LL; const int inf = 1e9+1e8; const int N=1e5+100; const ll mod=1e9+7; int n,m,w[505],re[1005],vis[505]; stack<int> st,st0; int main(){ ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); cin>>n>>m; for(int i=1; i<=n; ++i){ cin>>w[i]; } for(int i=1; i<=m; ++i){ cin>>re[i]; if(!vis[re[i]]){ st0.push(re[i]); vis[re[i]]=1; } } while(!st0.empty()){ st.push(st0.top()); st0.pop(); } ll ans=0; for(int i=1; i<=m; ++i){ while(st.top()!=re[i]){ st0.push(st.top()); ans+=w[st.top()]; st.pop(); } int tp=st.top(); st.pop(); while(!st0.empty()){ st.push(st0.top()); st0.pop(); } st.push(tp); } cout<<ans<<endl; return 0; } /* 10 10 61 59 97 16 2 94 57 48 91 93 2 8 6 5 3 1 3 4 9 10 */