1686. Stone Game VI

题目:

Alice and Bob take turns playing a game, with Alice starting first.

There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.

You are given two integer arrays of length naliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.

The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally.

Determine the result of the game, and:

  • If Alice wins, return 1.
  • If Bob wins, return -1.
  • If the game results in a draw, return 0.

Example 1:

Input: aliceValues = [1,3], bobValues = [2,1]
Output: 1
Explanation:
If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
Bob can only choose stone 0, and will only receive 2 points.
Alice wins.

Example 2:

Input: aliceValues = [1,2], bobValues = [3,1]
Output: 0
Explanation:
If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
Draw.

Example 3:

Input: aliceValues = [2,4,3], bobValues = [1,6,7]
Output: -1
Explanation:
Regardless of how Alice plays, Bob will be able to have more points than Alice.
For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
Bob wins.

Constraints:

  • n == aliceValues.length == bobValues.length
  • 1 <= n <= 10^5
  • 1 <= aliceValues[i], bobValues[i] <= 100

思路:

这题首先纯贪心是不行的,如例二,Alice是[1, 2],Bob是[3, 1],按照贪心,A抢2,B抢3,那A就输了。因此我们可以看出,对于一块石头,如果它对于A的价值很高,A会想要;如果它对于B的价值也很高,A还是会想要它,因为否则被B抢走就输了。那如何去考虑这个石头的价值呢,我们用两人价值和考虑,当这个石头的价值和高,A就很想要,因此我们按照和对于数列排序,同时我们还需要记住当前和中,A的价值是多少,B的价值是多少。这个地方可以用vector<vector<int>>,里面装[A价值+B价值,A价值,B价值],然后来sort,也可以用map<int,pair<int,int>>,里面也是存这三个,都差不多。然后遍历这个和数组,当i被2整除时,A拿,否则B拿,看最后价值。这里i被2整除A拿是因为A先手,一人拿一次但是要保证i=0时是A拿。

代码:

class Solution {
public:
    static bool comp(vector<int>&a , vector<int>&b)
    {
        return a[0]>b[0];
    }
    int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) {
        vector<vector<int>> record;
        int n=aliceValues.size();
        for(int i=0;i<n;i++)
            record.push_back({aliceValues[i]+bobValues[i],aliceValues[i], bobValues[i]});
        sort(record.begin(),record.end(),comp);
        int a=0, b=0;
        
        for(int i=0;i<n;i++)
        {
            if(i%2==0)
                a+=record[i][1];
            else
                b+=record[i][2];
        }
        return a==b?0:a>b?1:-1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_49991368/article/details/111147968