蓝桥杯 ADV-139 算法提高 种树

算法提高 种树

时间限制:1.0s 内存限制:256.0MB

问题描述

  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

#include <stdio.h>

int n, m;
int A[35];
int current_beauty, max_beauty;
int tree_position[35];

int abs(int x)
{
    return x > 0 ? x : -x;
}

int is_valid(int pos, int num_trees)
{
    for (int i = 0; i < num_trees; ++i)
    {
        if (pos == tree_position[i] ||
                abs(pos - tree_position[i]) == 1 ||
                (pos == 0 && tree_position[i] == n - 1) ||
                (pos == n - 1 && tree_position[i] == 0))
            return 0;
    }
    return 1;
}

void plant(int now_pos, int has_planted)
{
    if (has_planted == m)
    {
        if (current_beauty > max_beauty)
            max_beauty = current_beauty;
        return;
    }

    if (now_pos >= n)
        return;

    if (is_valid(now_pos, has_planted))
    {
        tree_position[has_planted] = now_pos;
        current_beauty += A[now_pos];
        plant(now_pos + 1, has_planted + 1);
        current_beauty -= A[now_pos];
    }
    plant(now_pos + 1, has_planted);
}

int main()
{
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; ++i)
        scanf("%d", &A[i]);

    if (m <= n / 2)
    {
        current_beauty = 0;
        max_beauty = -0x3F3F3F3F;
        plant(0, 0);
        printf("%d", max_beauty);
    }
    else
        printf("Error!");

    return 0;
}
发布了358 篇原创文章 · 获赞 46 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/liulizhi1996/article/details/104412915