C语言/C++常见习题问答集锦(六十六) 之x对应y的函数值与Nim取子游戏博弈论
程序之美
1、已知:y是x的函数,
当x<10时,y=-x;
当x=10时,y=31;
当x>10,且x<=100时,y=3x-7;
当x>100时,y= x2-5x+1;
输入格式:
任意输入一个int类型的整数x。
输出格式:
输出为一个整数,单独占一行,即x对应的函数值。
输入样例:
5
结尾无空行
输出样例:
-5
结尾无空行
解法一:
#include <stdio.h>
int main()
{
int x=0,y=0;
scanf("%d",&x);
if(x<10)y=-x;
else if(x==10) y=31;
else if(x>10&&x<=100) y=3*x-7;
else if(x>1000) y=x*x-5*x+1;
printf("%d",y);
return 0;
}
解法二:
#include<stdio.h>
int main(){
int x, y;
scanf("%d", &x);
if (x < 10)
{
y = -x;
}
else if (x == 10)
{
y = 31;
}
else if (x > 10 && x <= 100)
{
y = 3 * x - 7;
}
else {
y = x * x - 5 * x + 1;
}
printf("%d\n", y);
return 0;
}
运行结果:
2、c++ Nim取子游戏 博弈论
Problem description:
There are N heaps of coins on the table ordered in a row. In the i-th heap there are exactly ai coins.
Additionally, it is known that ai ≤ aj if i < j.
Alice and Bob play a game with these coins. At each move it is allowed to take any positive amount of coins from any heap, but the condition (ai ≤ aj if i < j) must remain satisfied. The player who takes the last coin, wins.
You should find who wins if no one makes a mistake and Bob gets to make the first move.
Input
The input consists of
• one line containing N (1 ≤ N ≤ 10^5) – the number of heaps
• one line containing N numbers a1, a2, …, aN (1 ≤ ai ≤ 10^9) – the sizes of the heaps.
Output
If Bob wins output “Bob", otherwise output “Alice".
解法一:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
scanf("%d",&n);
if(n%(3+1)==0)
printf("falsee\n");
else
printf("true\n");
return 0;
}
解法二:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
/*
Lose First :a1 ^ a2 ^ a3 ^ ... ^an = 0
Win First:a1 ^ a2 ^ a3 ^ ... ^an ≠ 0
*/
int main()
{
int n;
cin >> n;
int res = 0;
while (n--)
{
int a;
cin >> a;
res ^= a;
}
if (res) puts("Bob");
else puts("Alice");
return 0;
}