สมมติว่ามีเกมสำหรับผู้เล่นสองคนที่มี n รอบ คะแนนของรอบจะได้รับใน 'คะแนน' ของอาร์เรย์ โดยที่แต่ละองค์ประกอบอยู่ในรูปแบบ {คะแนน P1 คะแนน P2} ผู้เล่นที่มีคะแนนสูงกว่าจะชนะรอบหนึ่ง และผู้เล่นจะชนะเกมหากพวกเขาชนะรอบมากกว่านั้น มิฉะนั้นจะประกาศเป็นเสมอ ดังนั้น เมื่อดูจากคะแนนแล้ว เราต้องหาว่าใครชนะเกมนี้
ดังนั้น หากอินพุตเป็น n =4 คะแนน ={{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