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
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;
}

좋은 웹페이지 즐겨찾기