这道题直接模拟即可,我也不是很懂为什么放在队列和栈里,估计学长是想让我们用栈和队列写吧。但是个人觉得数组更好理解,其实栈和队列跟数组本质上都差不多。
1 #include <bits/stdc++.h> 2 #define maxn 5000 + 10 3 int main(){ 4 int in; 5 while (~scanf("%d", &in)){ 6 while (in--){ 7 int left, a[maxn], b[maxn], c[maxn], num; 8 int flag = 1; 9 scanf("%d", &num); 10 left = num; 11 int r = 0; 12 for(int i = 0; i < num; i++) 13 a[i] = i+1, b[i] = i, c[i] = 1; 14 15 if(left <= 3){ 16 for (int i = 0; i < left; i++){ 17 if(r) printf(" %d", a[i]); 18 else printf("%d", a[i]); 19 r = 1; 20 }printf("\n"); 21 }else { 22 int j = 0; 23 for (int i = 0; i < num; i++) 24 if(c[i]) b[j++] = i; 25 26 while (left > 3){ 27 int j = 0; 28 if (flag){ 29 for(int i = 1; i < left; i+=2) 30 c[b[i]] = 0; 31 left =left - left / 2; 32 } else { 33 for(int i = 2; i < left; i+=3) 34 c[b[i]] = 0; 35 left = left - left / 3; 36 } 37 flag = !flag; 38 for(int i = 0; i < num; i++) if(c[i]) b[j++] = i; 39 r = 0; 40 } 41 for(int i = 0; i < left; i++) 42 { 43 if(r) printf(" %d", a[b[i]]); 44 else printf("%d", a[b[i]]); 45 r = 1; 46 } 47 printf("\n"); 48 } 49 } 50 } 51 return 0; 52 }