例题3-5,例题4-2,例题4-3
Posted ton2018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了例题3-5,例题4-2,例题4-3相关的知识,希望对你有一定的参考价值。
例题3-5生成元
1 #include <stdio.h> 2 #include <string.h> 3 #define maxn 100005 4 int ans[maxn]; 5 6 int main() { 7 int T, n; 8 memset(ans, 0, sizeof(ans)); 9 for (int m = 1; m < maxn; m++) { 10 int x = m, y = m; 11 while (x > 0) { 12 y += x % 10; 13 y /= 10; 14 } 15 if(ans[y] == 0 || m < ans[y]) 16 ans[y] = m; 17 } 18 scanf("%d", &T); 19 while(T--) { 20 scanf("%d", &n); 21 printf("%d\n", ans[n]); 22 } 23 return 0; 24 }
例题4-2 刽子手游戏
#include <stdio.h> #include <string.h> #define maxn 100 int left, chance; //还需猜测left个位置,错chance次之后就输了 char s[maxn], s2[maxn]; //答案是字符串s,玩家猜的字母序列是s2 int win, lose; //win=1表示已经赢了;lose=1表示已经输了 void guess(char ch) { int bad = 1; for(int i = 0; i < strlen(s); i++) { if(s[i] == ch) { left--; s[i] = ‘ ‘; bad = 0; } if(bad) --chance; if(!chance) lose = 1; if(!left) win = 1; } } int main() { int rnd; while (scanf("%d%s%s",&rnd, s, s2) == 3 && rnd != -1) { printf("Round %d\n", rnd); win = lose = 0; //求解一组新数据之前要初始化 left = strlen(s); chance = 7; for (int i = 0; i < strlen(s2); i++) { guess(s2[i]); //猜测一个字母 if(win || lose) //检查状态 break; } if(win) printf("You win.\n"); else if(lose) printf("You lose.\n"); else printf("You chickened out.\n"); } return 0; }
例题4-3救济金发放
#include <stdio.h> #define maxn 25 int n, k, m, a[maxn]; //逆时针走t步,步长是d(-1表示顺时针走),返回新位置 int go(int p, int d, int t) { while (t--) { do { p = (p+d+n-1) %n + 1; }while(a[p] == 0); //走到下一个非0数字 } return p; } int main() { while (scanf("%d%d%d", &n, &k, &m) == 3 && n) { for (int i = 1; i <= n; i++) a[i] = i; int left = n; int p1 = n, p2 = 1; while(left) { p1 = go(p1, 1, k); p2 = go(p2, -1, m); printf("%3d", p1); left--; if(p2 != p1) { printf("%3d", p2); left--; } a[p1] = a[p2] = 0; if (left) printf(","); } printf("\n"); } return 0; }
以上是关于例题3-5,例题4-2,例题4-3的主要内容,如果未能解决你的问题,请参考以下文章
例题3-5 Digit Generator UVA - 1583