#785. 徐老师的石子游戏


一,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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值