📌  相关文章
📜  寻找游戏的获胜者

📅  最后修改于: 2021-04-29 03:42:17             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,两个玩家AB正在玩一个游戏,其中玩家选择自己的回合中位数最大的元素。最后,具有最大被选元素总和的玩家赢得游戏。假设玩家A总是首先开始游戏,并且两个玩家都进行了最佳比赛,那么任务就是找到游戏的获胜者。

例子:

方法:根据整数的数字总和值对数组进行排序,如果两个整数的数字总和相同,则将根据它们的值对它们进行比较,这是因为该值将最终使总和最大化。在根据自定义比较器对数组进行排序后,玩家A将尝试从最大(贪婪地)开始选择元素。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function that returns the
// sum of the digits of n
int digit_sum(int n)
{
    int s = 0;
    while (n > 0) {
        s += n % 10;
        n /= 10;
    }
    return s;
}
  
// Compares two integers according
// to their digit sum
bool comparator(int a, int b)
{
  
    // Sum of digits of a
    int s1 = digit_sum(a);
  
    // Sum of digits of b
    int s2 = digit_sum(b);
  
    // If the digit sum of a is equal
    // to the digit sum of b
    if (s1 == s2)
        return (a < b);
    return (s1 < s2);
}
  
// Function to return the winner of the game
string findTheWinner(int arr[], int n)
{
  
    // Sort the elements based on
    // the digit sum values
    sort(arr, arr + n, comparator);
  
    // Find player A's score
    int scoreA = 0;
    for (int i = n - 1; i >= 0; i -= 2)
        scoreA += arr[i];
  
    // Find player A's score
    int scoreB = 0;
    for (int i = n - 2; i >= 0; i -= 2)
        scoreB += arr[i];
  
    // Find the winner
    if (scoreA == scoreB)
        return "Draw";
    else if (scoreA > scoreB)
        return "A";
    return "B";
}
  
// Driver code
int main()
{
    int arr[] = { 12, 43, 25, 23, 30 };
    int n = sizeof(arr) / sizeof(int);
  
    cout << findTheWinner(arr, n);
  
    return 0;
}


Python3
# Python3 implementation of the above approach 
  
# Function that returns the 
# sum of the digits of n 
def digit_sum(n): 
      
    s = 0; 
    while n > 0: 
        s += n % 10
        n /= 10
          
    return s
  
# Function to return the winner 
# of the game 
def findTheWinner(arr, n):
  
    # Sort the elements based on 
    # the digit sum values 
    arr.sort(key = digit_sum)
  
    # Find player A's score 
    scoreA = 0
    i = n - 1
    while i >= 0:
        scoreA += arr[i]
        i -= 2
  
    # Find player A's score 
    scoreB = 0
    i = n - 2
    while i >= 0:
        scoreA += arr[i]
        i -= 2
  
    # Find the winner 
    if scoreA == scoreB: 
        return "Draw"
    elif (scoreA > scoreB): 
        return "A"
          
    return "B"
  
# Driver code 
if __name__=="__main__":
      
    arr = [ 12, 43, 25, 23, 30 ]
    n = len(arr); 
  
    print(findTheWinner(arr, n)) 
      
# This code is contributed by Yash_R


输出:
A