# 三珠互斥

  1. 如果k * 3 大于 n 了,那说明一定没结果,如果没想明白,大家举个例子试试看
  2. 分别求出三个红珠子之间的距离
  3. 对这三段距离从小到大排序 y1, y2, y3
  4. 如果第一段距离y1 小于k,说明需要交换 k - y 次, 同理 第二段距离y2 小于k,说明需要交换 k - y2 次
  5. y1 y2 都调整好了,不用计算y3,因为 y3是距离最大
#include<bits/stdc++.h>
using namespace std;
 
int main(){
    int t;
    cin >> t;
    int n, k, a1, a2, a3;
    vector<int> dis(3);

    while (t--) {
        cin >> n >> k >> a1 >> a2 >> a3;
        if(k * 3 > n){
            cout << -1 << endl;
            continue;
        }
        dis[0] = min(abs(a1 - a2), n - abs(a1 - a2));
        dis[1] = min(abs(a1 - a3), n - abs(a1 - a3));
        dis[2] = min(abs(a3 - a2), n - abs(a3 - a2));

        sort(dis.begin(), dis.end());

        int result = 0;
        if (dis[0] < k) result += (k - dis[0]);
        if (dis[1] < k) result += (k - dis[1]);

        cout << result << endl;
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Java代码:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();

        while (t-- > 0) {
            int n = scanner.nextInt();
            int k = scanner.nextInt();
            int a1 = scanner.nextInt();
            int a2 = scanner.nextInt();
            int a3 = scanner.nextInt();
            if (k * 3 > n) {
                System.out.println(-1);
                continue;
            }

            List<Integer> dis = new ArrayList<>(3);
            dis.add(Math.min(Math.abs(a1 - a2), n - Math.abs(a1 - a2)));
            dis.add(Math.min(Math.abs(a1 - a3), n - Math.abs(a1 - a3)));
            dis.add(Math.min(Math.abs(a3 - a2), n - Math.abs(a3 - a2)));

            Collections.sort(dis);

            int result = 0;
            if (dis.get(0) < k) result += (k - dis.get(0));
            if (dis.get(1) < k) result += (k - dis.get(1));

            System.out.println(result);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
上次更新:: 3/4/2025, 5:49:45 PM
@2021-2025 代码随想录 版权所有 粤ICP备19156078号