查找赢得了 n 轮游戏的赢家的 C++ 代码


假设有一个双人游戏包含 n 轮。各轮分数保存在数组'scores'中,其中每个元素的格式为{{P1 得分,P2 得分}。得分较高的那位玩家赢得了该轮比赛,如果一位玩家赢得的轮次更多,则该玩家赢得游戏;否则,则宣布为平局。因此,根据得分,我们需要找出谁赢得了这场游戏。

因此,如果输入为 n = 4, scores = {{4, 3}, {3, 2}, {5, 6}, {2, 5}},则输出将为平局。

步骤

要解决这个问题,我们将按照以下步骤进行操作 −

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

更新于: 11-Mar-2022

356 次浏览

开启你的 事业

通过完成课程获得认证

开始
广告
© . All rights reserved.