查詢贏得了 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP