有一个游戏是这样玩的,给出一列数字.首先由你在其中任意选择一个数字,然后轮到你的对手选择数字,但他只能从你上一步选择的数字的左边或右边选择一个,之后你也只能从对手上一步选择的数字的左边或右边去选择,直到大家挑选完所有的数字。最后看谁选择的数字总和最大,谁就获胜。 如果一直让你第一个挑选数字,那么你能保证无论有多少个数字,数字怎么排列,你总能赢得比赛吗?
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
int player1Score = 0;
int player2Score = 0;
int leftIndex = 0;
int rightIndex = numbers.size() - 1;
bool player1Turn = true;
while (leftIndex <= rightIndex) {
int choice;
if (player1Turn) {
std::cout << "Player 1, enter your choice (1 for left, 2 for right): ";
std::cin >> choice;
if (choice == 1) {
player1Score += numbers[leftIndex];
leftIndex++;
} else {
player1Score += numbers[rightIndex];
rightIndex--;
}
} else {
std::cout << "Player 2, enter your choice (1 for left, 2 for right): ";
std::cin >> choice;
if (choice == 1) {
player2Score += numbers[leftIndex];
leftIndex++;
} else {
player2Score += numbers[rightIndex];
rightIndex--;
}
}
player1Turn = !player1Turn;
}
std::cout << "Player 1 score: " << player1Score << std::endl;
std::cout << "Player 2 score: " << player2Score << std::endl;
if (player1Score > player2Score) {
std::cout << "Player 1 wins!" << std::endl;
} else if (player2Score > player1Score) {
std::cout << "Player 2 wins!" << std::endl;
} else {
std::cout << "It's a tie!" << std::endl;
}
return 0;
}