49分求解
查看原帖
49分求解
604006
CuteGhost楼主2023/3/8 13:48
package com.tao;

import java.util.Scanner;

public class dfs4 {
    static int[] arr ;
    static boolean[] st;
    static int k;
    static int sum;
    static int num;
    static int n;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n=sc.nextInt();
        k=sc.nextInt();
        arr = new int[n+1];
        st = new boolean[n+1];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        dfs(0,1);
        System.out.println(num);
    }
    public static void dfs(int q,int start){
        if(q==k){
            if(isPrime(sum)){
                num++;
            }
        }
        for (int i = start; i <= n; i++) {
            if(!st[i]){
                sum+=arr[q];
                st[i] = true;
                dfs(q+1,i);
                st[i] = false;
                sum-=arr[q];
            }
        }
    }
    public static boolean isPrime(int sum){
        for (int i = 2; i < sum/i; i++) {
            if(sum%i==0){
                return false;
            }
        }
        return true;
    }
}

2023/3/8 13:48
加载中...