题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=6707
题目:
A deck of card consists of n cards. Each card is different, numbered from 1 to n. At first, the cards were ordered from 1 to n. We complete the shuffle process in the following way, In each operation, we will draw a card and put it in the position of the first card, and repeat this operation for m times.
Please output the order of cards after m operations.
Input
The first line of input contains two positive integers n and m.(1<=n,m<=105)
The second line of the input file has n Numbers, a sequence of 1 through n.
Next there are m rows, each of which has a positive integer si, representing the card number extracted by the i-th operation.
Output
Please output the order of cards after m operations. (There should be one space after each number.)
Sample Input
5 3
1 2 3 4 5
3
4
3
Sample Output
3 4 1 2 5
题意:有一叠纸牌,每张都不一样。刚开始的时候将纸牌是从1到n开始排序。接下来我们要开始洗牌操作,每一次都将一个纸牌放在最上面,重复这个操作m次。输出m次操作后的顺序。
题解:先使用两倍范围大的数组a储存纸牌,需要注意的是,数组a要从末尾开始保存,输出也是从末尾开始的,也就是说把末尾当成纸牌的上方(起始位置)。(这其实就是栈的思想吧,所以也可以用stack容器来做的。)再用book数组来存储各个纸牌的位置。在进行m操作的时候只需要将原来数组a中存储纸牌的位置改为-1,然后在数组a末尾添加数据即可。最后输出的时候只需要判断数组a是否为-1就好了。
代码及注释如下:
#include<iostream>
#include<cstring>
using namespace std;
int a[200005],book[100005];
int main() {
int n,m,tmp;
ios::sync_with_stdio(false);
cin>>n>>m;
memset(book,0,sizeof(book));
for(int i=n;i>=1;i--) {//从n开始输入,重点!!!
cin>>a[i];
book[a[i]]=i;//纸牌位置初始化
}
int top=n;//纸牌末尾
for(int i=1;i<=m;i++) {
cin>>tmp;
a[book[tmp]]=-1;//原来位置改为-1
book[tmp]=++top;//数组a末尾为纸牌新位置
a[book[tmp]]=tmp;//赋值
}
for(int i=top;i>=1;i--) {
if(a[i]==-1) continue;
cout<<a[i]<<' ';//pe点,末尾加空格
}
return 0;
}