Queues
Card Games
There is a stack of cards on the table, starting with the first card (that is, the card at the top) to be numbered 1-n. When you have at least two cards left, do the following: Throw the first card away and put the new first one at the end of the stack. Enter n, output the cards thrown each time, and the last remaining cards.
Sample input: 7
Sample output: 1 3 5 7 4 2 6
# include<iostream>
# include<queue>
using namespace std;
queue<int> Q;
int main ()
{
int n;
cin>>n;
for (int i=0;i<n;i++)
Q.push (i+1);
while (!q.empty ())
{
cout<<q.front () << "";
Q.pop ();
Q.push (Q.front ());
Q.pop ();
}
return 0;
}
Stack
# include<cstdio>
# include<algorithm>
using namespace std;
const int MAXN=1000+10;
int TARGET[MAXN];
int main ()
{
int n;
while (scanf ("%d", &n) ==1)
{
int stack[maxn],top=0;
int a=1,b=1;
for (int i=1;i<=n;i++)
scanf ("%d", &target[i]);
int ok=1;
while (b<=n)
{
if (A==target[b]) {a++; b++;} No need c
else if (Top&&stack[top]==target[b]) {top--; b++;}
else if (a<=n) {stack[++top]=a++}
else {ok=0;break;}
}
printf ("%s\n", OK?) Yes ":" no ");
}
return 0;
}
using STL to implement stack
# include<cstdio> # include<algorithm> # include<stack> using namespace std
;
const int MAXN=1000+10;
int TARGET[MAXN];
int main () {int n;
while (scanf ("%d", &n) ==1) {//int stack[maxn],top=0;
Stack<int> s;
int a=1,b=1;
for (int i=1;i<=n;i++) scanf ("%d", &target[i]);
int ok=1; while (b<=n) {if (A==target[b]) {a++; b++;} No need C else if (!s.empty () && s.top () ==target[b]) {s.pop ();
b++;}
else if (a<=n) {s.push (a++);}
else {ok=0;break;} printf ("%s\n", OK?)
Yes ":" No ");
return 0; }