一,60分的解法(时间复杂度为O(n ^ 2))
用数组模拟双向链表,优点:因为要经常删除数据,所以只要O(1)就行了。
代码:
#include <bits/stdc++.h>
using namespace std;
int ans,n,sh[900001];
struct nod
{
int l,r,da;
} a[900001];
int main()
{
//freopen("stone.in","r",stdin);
//freopen("stone.out","w",stdout);
cin>>n;
for(int i = 1; i <= n; i++)
{
cin>>a[i].da;
a[i].l = i - 1;
a[i].r = i + 1;
}
for(int i = 1; i <= n; i++) cin>>sh[i];
for(int i = 1; i <= n; i++)
{
int j = 1;
while(sh[i] != a[j].da) j = a[j].r;
a[a[j].l].r = a[j].r;
a[a[j].r].l = a[j].l;
ans += a[a[j].r].da + a[a[j].l].da;
}
cout<<ans;
return 0;
}
//3 1 2 3 2 3 1
二,100分
能够做到快速删除的数据结构也就只有链表了,所以这道题可以用数组模拟双向链表,每次可
以快速知道一个数左右了两边是什么数,然后调整下左右两边连接的情况就可以了。注意:因为题目上说:
,所以要以石子数量为下标。
代码:
#include <bits/stdc++.h>
using namespace std;
int ans,n,sh[900001];
struct nod
{
int l,r,da;
} a[900001];
int main()
{
//freopen("stone.in","r",stdin);
//freopen("stone.out","w",stdout);
cin>>n;
for(int i = 1; i <= n; i++)
{
cin>>a[i].da;
a[i].l = i - 1;
a[i].r = i + 1;
}
for(int i = 1; i <= n; i++) cin>>sh[i];
for(int i = 1; i <= n; i++)
{
int j = 1;
while(sh[i] != a[j].da) j = a[j].r;
a[a[j].l].r = a[j].r;
a[a[j].r].l = a[j].l;
ans += a[a[j].r].da + a[a[j].l].da;
}
cout<<ans;
return 0;
}
//3 1 2 3 2 3 1