题:
You have a card deck of n cards, numbered from top to bottom, i. e. the top card has index 1 and bottom card — index n. Each card has its color: the i-th card has color ai.
You should process q queries. The j-th query is described by integer tj. For each query you should:
find the highest card in the deck with color tj, i. e. the card with minimum index;
print the position of the card you found;
take the card and place it on top of the deck.
Input
The first line contains two integers n and q (2≤n≤3⋅10^5; 1≤q≤3⋅10^5) — the number of cards in the deck and the number of queries.
The second line contains n integers a1,a2,…,an (1≤ai≤50) — the colors of cards.
The third line contains q integers t1,t2,…,tq (1≤tj≤50) — the query colors. It’s guaranteed that queries ask only colors that are present in the deck.
Output
Print q integers — the answers for each query.
Example
input
7 5
2 1 1 4 3 3 1
3 2 1 1 4
output
5 2 3 1 5
Note
Description of the sample:
1.the deck is
and the first card with color t1=3 has position 5;
2.the deck is
and the first card with color t2=2 has position 2;
3.the deck is
and the first card with color t3=1 has position 3;
4.the deck is
and the first card with color t4=1 has position 1;
5.the deck is
and the first card with color t5=4 has position 5.
题意:
第一行给两个整数n,q。
第二行给n个元素表示颜色,只有五十种颜色,一种颜色可重复出现。
第三行是询问次数q,每次询问该颜色最小的下标位置是多少。
思路:
一开始看感觉是个栈或者队列相关的问题,但是n和q是3*10^5,如果按照常规方法去搜寻、删除、移位,应该随随便便就超时了叭。
再多想想,颜色只有五十种,只要找到每个颜色变换后的最小下标输出就好了,基本上只关颜色第一次出现的位置的事,跟排列在后面相同的颜色没啥关系。
所以,只要先把每个颜色第一次出现的位置存在一个数组里面,然后每次查询输出下标后,把该颜色前面位置的颜色下标都加一,然后再把该颜色下标变成一就好啦。
#include<iostream>
#include<map>
using namespace std ;
int main()
{
ios::sync_with_stdio(false) ;
cin.tie(0) ;
cout.tie(0) ;
long n , q , i ;
cin >> n >> q ;
map< int , int > p ;
int a[55] = {0} , x ,b[300005] ;
for( i = 1 ; i <= n ; ++i )
{
cin >> x ;
p[x]++ ;
if( p[x] == 1 )
{
a[x] = i ;
}
}
for( i = 1 ; i <= q ; ++i )
cin >> b[i] ;
for( i = 1 ; i <= q ; ++i )
{
cout << a[b[i]] << " " ;
for( int j = 0 ; j < 53 ; ++j )
{
if( a[j] < a[b[i]] )
{
a[j]++ ;
}
}
a[b[i]] = 1 ;
}
cout << endl ;
return 0 ;
}