算法提高 种树

种树

问题描述
  A城市有一个巨大的圆形广场,为了绿化环境和净化空气,市政府决定沿圆形广场外圈种一圈树。园林部门 得到指令后,初步规划出n个种树的位置,顺时针编号1到n。并且每个位置都有一个美观度Ai,如果在这里种树就可以得到这Ai的美观度。但由于A城市土壤 肥力欠佳,两棵树决不能种在相邻的位置(i号位置和i+1号位置叫相邻位置。值得注意的是1号和n号也算相邻位置!)。
  最终市政府给园林部门提供了m棵树苗并要求全部种上,请你帮忙设计种树方案使得美观度总和最大。如果无法将m棵树苗全部种上,给出无解信息。
输入格式
  输入的第一行包含两个正整数n、m。
  第二行n个整数Ai。
输出格式
  输出一个整数,表示最佳植树方案可以得到的美观度。如果无解输出“Error!”,不包含引号。
样例输入
7 3
1 2 3 4 5 6 7
样例输出
15
样例输入
7 4
1 2 3 4 5 6 7
样例输出
Error!
数据规模和约定
  对于全部数据,满足1<=m<=n<=30;
  其中90%的数据满足m<=n<=20
  -1000<=Ai<=1000
 1 import java.math.BigInteger;
 2 import java.util.Arrays;
 3 import java.util.Scanner;
 4 
 5 
 6 public class Main {
 7     static int n;
 8     static int[] a;
 9     static boolean[] b;
10     static int max;
11     static boolean flag;
12     public static void main(String[] args) {
13         Scanner input = new Scanner(System.in);
14         n = input.nextInt();
15         int m = input.nextInt();
16         a = new int[n];
17         for(int i=0;i<n;i++){
18             a[i] = input.nextInt();
19         }
20         b = new boolean[n];    
21         f(m,0,0);
22         if(flag) System.out.println(max);
23         else System.out.println("Error!");
24     }
25     public static void f(int i,int j,int sum){
26         if(i==0&&j<=n){
27             if(max<sum) max = sum;
28             flag  = true;
29             return;
30         }
31         for(int h=j;h<n;h++){
32             if(b[h]==false){
33                 if(h<n-1) b[h+1] = true;
34                 if(h==0){b[n-1] = true;b[h] = true;} 
35                 f(i-1,h+1,sum+a[h]);
36                 if(h<n-1) b[h+1] = false;
37                 if(b[0]==true)    b[n-1] = true;
38                 if(h==0){b[n-1] = false;b[h] = false;} 
39             }
40         }
41         
42 
43     }
44 }
原文地址:https://www.cnblogs.com/lolybj/p/6633925.html