Wannafly挑战赛 19 A.队列Q(思维)

xiaoxiao2021-02-28  57

题目链接:https://www.nowcoder.com/acm/contest/131/A

       这道题刚开始我的想法是用两个栈分别去存FIRST和LAST所操作的数,用map标记入栈的数,然后先将FIRST栈中的数输出,然后再遍历数组输出没有被标记的数,最后再输出LAST栈中的数,虽然我觉得没什么问题吧,但是只过了5%的样例。能AC的方法就是首先我们要从100000开始输入数据(至于为什么等会再说),然后用map去标记这个数的当前位置。然后进行操作的时候,如果是FIRST我们就从100000往前存这个数,如果是LAST我们就从100000+n开始往后继续存数,同时需要更新map的标记,最后我们只需要输出map所标记的值就好了。

       因为可能会有100000个FIRST个操作,所以最开始输入数的时候下标要大于等于100000...

       emmmmm...先贴一个我认为没什么毛病的代码

过了5%样例的代码:

#include <iostream> #include <cstdio> #include <cstring> #include <map> using namespace std; map<int,int> ma; int n,m; int l = 100000; int pre[300005]; int main() { scanf("%d",&n); int r; for(r=l;r<l+n;r++){ scanf("%d",&pre[r]); ma[pre[r]] = r; } r--; scanf("%d",&m); while(m--){ string str; int x; cin>>str; scanf("%d",&x); if(str == "FIRST"){ pre[--l] = x; ma[x] = l; } else{ pre[++r] = x; ma[x] = r; } } for(int i=l;i<=r;i++){ if(ma[pre[i]] == i){ printf("%d%c",pre[i],i==r-1?'\n':' '); } } return 0; }

AC代码:

#include <iostream> #include <cstdio> #include <cstring> #include <map> using namespace std; map<int,int> ma; int n,m; int l = 100000; int pre[300005]; int main() { scanf("%d",&n); int r; for(r=l;r<l+n;r++){ scanf("%d",&pre[r]); ma[pre[r]] = r; } r--; scanf("%d",&m); while(m--){ string str; int x; cin>>str; scanf("%d",&x); if(str == "FIRST"){ pre[--l] = x; ma[x] = l; } else{ pre[++r] = x; ma[x] = r; } } int num = 0; for(int i=l;i<=r;i++){ if(ma[pre[i]] == i){ num++; printf("%d%c",pre[i],num==n?'\n':' '); } } return 0; }
转载请注明原文地址: https://www.6miu.com/read-2614468.html

最新回复(0)