题解 | #素数伴侣# 学习解题思路

素数伴侣

https://www.nowcoder.com/practice/b9eae162e02f4f928eac37d7699b352e

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            int n = Integer.parseInt(reader.readLine());
            String[] nums = reader.readLine().split(" ");

            // 将输入的正整数存入数组
            int[] numbers = new int[n];
            for (int i = 0; i < n; i++) {
                numbers[i] = Integer.parseInt(nums[i]);
            }

            // 计算最佳方案组成素数伴侣的对数
            int count = findMains(numbers);
            System.out.println(count);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 判断一个数是否为素数
    public static boolean isPrime(int num) {
        if (num < 2) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    // 使用匈牙利算法寻找素数伴侣
    public static int findMains(int[] numbers) {
        int count = 0;
        int[] match = new int[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            match[i] = -1;
        }
        for (int i = 0; i < numbers.length; i++) {
            boolean[] visited = new boolean[numbers.length];
            if (find(numbers, i, match, visited)) {
                count++;
            }
        }
        return count / 2; // 每对素数伴侣会被计算两次,因此需要除以2
    }

    // 匈牙利算法实现
    public static boolean find(int[] numbers, int i, int[] match, boolean[] visited) {
        for (int j = 0; j < numbers.length; j++) {
            if (!visited[j] && isPrime(numbers[i] + numbers[j])) {
                visited[j] = true;
                if (match[j] == -1 || find(numbers, match[j], match, visited)) {
                    match[j] = i;
                    return true;
                }
            }
        }
        return false;
    }
}

全部评论

相关推荐

双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
10-22 15:25
门头沟学院 C++
种花网友小松:求求你别发了,我几乎都快嫉妒得疯了,倒在床上蒙住被子就开始抱着枕头尖叫流泪,嘴里一边喊着卧槽卧槽,一边又忍着,我边发边哭,打字的手都是抖的,后来我的手抖得越来越厉害,从心头涌起的思想、情怀和梦想,这份歆羡和悔恨交织在一起,我的笑还挂在脸上,可是眼泪一下子就掉下来了。求你了别发了,我生活再难再穷我都不会觉得难过,只有你们发这种东西的时候,我的心里像被刀割一样的痛,打着字泪水就忍不住的往下流。
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务