《算法竞赛入门经典》6.1的题目。题目大意:给n张牌,放成一叠,从上到下编号从1到n,当至少还有两张牌时,丢弃最上面的牌,然后把新的最上面的牌放到最下面,一直重复,直到只剩下一张牌,输出丢弃牌的序列。
用队列进行模拟,不过第一次提交的时候PE了,格式说明一下:
”Discarded cards:“,然后每一数字前加一个空格,第一个数字之后的数字要在空格前加逗号。代码如下:
View Code
1 #include2 #include 3 #include 4 using namespace std; 5 6 const int maxn = 60; 7 queue q; 8 9 int main()10 {11 #ifdef LOCAL12 freopen("in", "r", stdin);13 #endif14 int n;15 int ans[maxn];16 while(scanf("%d", &n) != EOF && n)17 {18 for(int i = 1; i <= n; i++) q.push(i);19 int k = 0;20 while(!q.empty())21 {22 ans[k++] = q.front();23 q.pop();24 int t = q.front();25 q.pop();26 q.push(t);27 }28 printf("Discarded cards:");29 for(int i = 0; i < n-1; i++)30 {31 if(i) printf(",");32 printf(" %d", ans[i]);33 }34 printf("\nRemaining card: %d\n", ans[n-1]);35 }36 return 0;37 }38