题目链接:https://www.dotcpp.com/oj/problem1551.html

    题目分析:

    • 给定n 个种树的位置(每个位置都有一个美观度) 和 m 个树苗,并且要求每一个树的左右必须为空,求最大美观度(需要判断种不下的情况)。
    • 对于每个位置有两种选择, or 不种,直接暴力搜索找种的下的情况下的最大值。
    1. import java.util.*;
    2. public class Main{
    3. public static int ans = Integer.MIN_VALUE;
    4. public static boolean[] visited;
    5. public static void dfs(int[] arr, int n, int m, int i, int total){
    6. if(m == 0){
    7. ans = Math.max(ans, total);
    8. return;
    9. }
    10. if(i >= n){
    11. return;
    12. }
    13. //选当前位置
    14. if(!visited[i] && !visited[(i-1+n) % n] && !visited[(i+1) % n]){
    15. visited[i] = true;
    16. dfs(arr, n, m-1, i+1, total + arr[i]);
    17. visited[i] = false;
    18. }
    19. //不选当前位置
    20. dfs(arr, n, m, i+1, total);
    21. }
    22. public static void main(String[] args) {
    23. Scanner sc = new Scanner(System.in);
    24. int n = sc.nextInt();
    25. int m = sc.nextInt();
    26. int[] arr = new int[n];
    27. visited = new boolean[n];
    28. for(int i = 0; i < n; i ++){
    29. arr[i] = sc.nextInt();
    30. }
    31. dfs(arr, n, m, 0, 0);
    32. if(ans == Integer.MIN_VALUE){
    33. System.out.println("Error!");
    34. }else{
    35. System.out.println(ans);
    36. }
    37. }
    38. }