Educational Codeforces Round 79 (Rated for Div. 2) C. Stack of Presents

链接:

https://codeforces.com/contest/1279/problem/C

题意:

Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a1, the next present is a2, and so on; the bottom present has number an. All numbers are distinct.

Santa has a list of m distinct presents he has to send: b1, b2, ..., bm. He will send them in the order they appear in the list.

To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are k presents above the present Santa wants to send, it takes him 2k+1 seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).

What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.

Your program has to answer t different test cases.

思路:

记录向下拿到的最深位置,低于这个位置可以排序后再拿,否着就要全部拿出来,记录拿出去的个数。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;

int Pos[MAXN];
int a[MAXN], b[MAXN];
int n, m;

int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n >> m;
        for (int i = 1;i <= n;i++)
        {
            cin >> a[i];
            Pos[a[i]] = i;
        }
        for (int i = 1;i <= m;i++)
            cin >> b[i];
        int maxp = 0;
        LL sum = 0;
        for (int i = 1;i <= m;i++)
        {
            if (Pos[b[i]] < maxp)
                sum++;
            else
            {
                sum += (Pos[b[i]]-i)*2;
                sum++;
                maxp = Pos[b[i]];
            }
        }
        cout << sum << endl;
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/YDDDD/p/12113507.html