假设有一个有 n 轮的两人游戏。回合的分数以数组“分数”的形式给出,其中每个元素的格式为 {P1 分数,P2 分数}。得分较高的玩家赢得一局,赢得更多回合的玩家获胜;否则,它被宣布为平局。因此,根据分数,我们必须找出谁赢得了比赛。
所以,如果输入像 n = 4,scores = {{4, 3}, {3, 2}, {5, 6}, {2, 5}},那么输出将是 Draw。
脚步
为了解决这个问题,我们将遵循以下步骤 -
res := 0 while n is non-zero, do: a := first value of scores[n] b := second value of scores[n] res := res + ((if a > b, then 1, otherwise (if a < b, then -1, otherwise 0))) n := n - 1 return (if res > 0, then "P1", otherwise (if res < 0, then "P2", otherwise "Draw"))
示例
让我们看看以下实现以更好地理解 -
#include <bits/stdc++.h> using namespace std; #define N 100 string solve(int n, vector<pair<int, int>> scores) { int res = 0; while(n--){ int a = scores[n].first; int b = scores[n].second; res += (a > b ? 1 : (a < b ? -1 : 0)); } return res > 0 ? "P1" : (res < 0 ? "P2" : "Draw"); } int main() { int n = 4; vector<pair<int, int>> scores = {{4, 3}, {3, 2}, {5, 6}, {2,5}}; cout<< solve(n, scores); return 0; }
输入
4, {{4, 3}, {3, 2}, {5, 6}, {2, 5}}输出结果
Draw