P1036 选数(DFS+不降原则去重)

import java.util.Scanner;

public class P1036{
	static int n,k,count=0;
	static int[] a ;
	static boolean[] flag ;
	static int[] b ;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		a = new int[n+1];
		flag = new boolean[n+1];
		b = new int[k+1];
		
		for(int i=1;i<=n;i++) {
			a[i] = sc.nextInt();
		}
		dfs(1,1);
		System.out.println(count);
	}

	private static void dfs(int pos,int starts) {
		if(pos==k+1) {
			int sum = 0;
			for(int j=1;j<=k;j++) {
				sum += b[j];
			}
			if(sum!=0&&isSuShu(sum)) {
				count++;
			}
			return;
		}
		for(int i=starts;i<=n;i++) {
			if(flag[i]==false) {
				b[pos] = a[i];
				flag[i] = true;
				dfs(pos+1,i+1);
				flag[i] = false;
 			}
		}
	}
	/**
	 * 判断一个数是否为素数
	 * @param sum
	 * @return
	 */
	private static boolean isSuShu(int sum) {
		for(int i=2;i<sum/2;i++) {
			if(sum%i==0) {
				return false;
			}
		}
		return true;
	}
	
}

 

上一篇:DC2靶机渗透测试


下一篇:P1036选数