练习codeforces2060C. Game of Mathletes

题目如下
C. Game of Mathletes
time limit per test2 seconds
memory limit per test256 megabytes
Alice and Bob are playing a game. There are 𝑛 (𝑛 is even) integers written on a blackboard, represented by 𝑥1,𝑥2,…,𝑥𝑛. There is also a given integer 𝑘 and an integer score that is initially 0. The game lasts for 𝑛2 turns, in which the following events happen sequentially:

Alice selects an integer from the blackboard and erases it. Let's call Alice's chosen integer 𝑎.
Bob selects an integer from the blackboard and erases it. Let's call Bob's chosen integer 𝑏.
If 𝑎+𝑏=𝑘, add 1 to score.
Alice is playing to minimize the score while Bob is playing to maximize the score. Assuming both players use optimal strategies, what is the score after the game ends?

Input
The first line contains an integer 𝑡 (1≤𝑡≤104) — the number of test cases.

The first line of each test case contains two integers 𝑛 and 𝑘 (2≤𝑛≤2⋅105,1≤𝑘≤2⋅𝑛, 𝑛 is even).

The second line of each test case contains 𝑛 integers 𝑥1,𝑥2,…,𝑥𝑛 (1≤𝑥𝑖≤𝑛) — the integers on the blackboard.

It is guaranteed that the sum of 𝑛 over all test cases does not exceed 2⋅105.

Output
For each test case, output the score if both players play optimally.
题目大意
题目是关于两个玩家a与b,a为先手,b后手,两人先后选择一个数,由a,b分别代表(选过的数不能被二次选择),若使得𝑎+𝑏=𝑘则游戏得分加1
a希望最小化得分,b则希望最大化得分;
在这样的条件下,求出最终得分
题目分析
虽然a希望最小化得分,b希望最大化得分,但这样的数对总数不会改变,况且a作为先手,b总能找到合法的数来配对,所以a,b的需求不参与考虑。
所以我们先对数组进行升序的排序,再采用双指针,双指针的使用要建立在数组单调的基础上,

点击查看代码
sort(a, a + n);
        int cnt = 0;
        int left = 0;
        int right = n - 1;
        while (left < right){
            int sum = a[left] + a[right];
            if (sum == k) {
                cnt++;
                left++;
                right--;
            }else if(sum < k){
                left++;
            }else{
                right--;
            }
        }

完整代码

点击查看代码
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        int n, k;
        int a[200005];
        scanf("%d%d", &n, &k);
        for(int i = 0; i < n; i++){
            scanf("%d", &a[i]);
        }
        sort(a, a + n);
        int cnt = 0;
        int left = 0;
        int right = n - 1;
        while (left < right){
            int sum = a[left] + a[right];
            if (sum == k) {
                cnt++;
                left++;
                right--;
            }else if(sum < k){
                left++;
            }else{
                right--;
            }
        }
        printf("%d\n", cnt);
    }
    return 0;
}
posted @ 2025-07-07 20:11  sirro1uta  阅读(9)  评论(0)    收藏  举报