-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCard_Rotation.cpp
72 lines (57 loc) · 1.72 KB
/
Card_Rotation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Given a sorted deck of cards numbered 1 to N.
// 1) We pick up 1 card and put it on the back of the deck.
// 2) Now, we pick up another card, it turns out to be card number 1, we put it outside the deck.
// 3) Now we pick up 2 cards and put it on the back of the deck.
// 4) Now, we pick up another card and it turns out to be card numbered 2, we put it outside the deck. ...
// We perform this step until the last card.
// If such an arrangement of decks is possible, output the arrangement, if it is not possible for a particular value of N then output -1.
// Example 1:
// Input:
// N = 4
// Output: 2 1 4 3
// Explanation:
// We initially have [2 1 4 3]
// In Step1, we move the first card to the end.
// Deck now is: [1 4 3 2]
// In Step2, we get 1. Hence we remove it. Deck
// now is: [4 3 2]
// In Step3, we move the 2 front cards ony by one
// to the end ([4 3 2] -> [3 2 4] -> [2 4 3]).
// Deck now is: [2 4 3]
// In Step4, we get 2. Hence we remove it. Deck
// now is: [4 3]
// In Step5, the following sequence follows:
// [4 3] -> [3 4] -> [4 3] -> [3 4]. Deck now
// is: [3 4]
// In Step6, we get 3. Hence we remove it. Deck
// now is: [4] Finally, we're left with a single
// card and thus, we stop.
// Example 2:
// Input:
// N = 5
// Output: 3 1 4 5 2
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
queue<int> q;
vector<int> res;
for(int i=0;i<n;i++){
q.push(i);
res.push_back(i+1);
}
vector<int> v(n,0);
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
int front=q.front();
q.pop();
q.push(front);
}
v[q.front()]=res[i];
q.pop();
}
for(int i:v){
cout<<i<<" ";
}
}