猪猪爱喝纯牛奶


私信TA

用户名:liaolingqian

访问量:3695

签 名:

等  级
排  名 2645
经  验 2124
参赛次数 1
文章发表 19
年  龄 0
在职情况 学生
学  校 ytu
专  业

  自我简介:

解题思路:

注意事项:dfs

参考代码:

import java.util.Scanner;


//DFS

public class llq1{

static final int maxn=35;

static int N=0;

static int M=0;

static int val[]=new int[maxn];

static boolean isPlanted[]=new boolean [maxn];//是否已经种了树

static int ans=0;

static int tmp=0;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

N=s.nextInt();

M=s.nextInt();

for(int i=1;i<N+1;i++) {

val[i]=s.nextInt();

}

if(M>N/2) {

System.out.println("Error!");

return;

}

dfs(1,0);

System.out.println(ans);

}

private static void dfs(int pos, int cnt) {//pos位置,cnt已经种了多少树

// TODO Auto-generated method stub

if(cnt==M) {

ans=Math.max(ans, tmp);

return;

}

for(int i=pos;i<=N;i++) {

if(check(i)) {

tmp+=val[i];

isPlanted[i]=true;

dfs(i,cnt+1);

isPlanted[i]=false;

tmp-=val[i];

}

}

}

private static boolean check(int pos) {//检查是否可以种树

// TODO Auto-generated method stub

if(pos>N||isPlanted[pos]||isPlanted[(pos+1)%N]||isPlanted[(pos-1)%N])

return false;

return true;

}

}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区