USACO Barn Repair

来源:互联网 发布:python 数据可视化js 编辑:程序博客网 时间:2024/06/15 20:24

题目大意:

给你C个点,M块木板,求把所有的点全覆盖的最短木板长度(每块木板不限长度)。

思路:

Ps:这道题真是想了一会, 贪心本来就不是本弱渣的长项。

既然是求把这些点全部覆盖的木板长度,还是给了木板的块数,其实这道题可以从小入手,比如 

2 3 5 这3个点,用两个木板覆盖, 那就有两个方案:2 3 一块 5 一块,和 2 一块 3 5 一块。

由此可以发现,其实本质就是从2 覆盖到 5 找到一个断点,而这个断点可以满足左边木板的和右边木板隔着尽量远的距离,也就是2 3 (断) 5 ,这样是最优的。

因为2 -> 3 距离为1,3 -> 5距离为2。

这样解决了2块木板的话,就可以递推到3块木板,因为第一次找到的断点是最优的,再在剩下的找到的还是最优的。

所以如果有m块木板的话,就是从第一个点覆盖到最后一个点,在其中找到两点距离最大的那m - 1块木板。

不过要注意两点:

1.点不是事先排好序的

2.木板数有可能大于点的数目(这样最优就是1个点1个木块,ans = C)

(这两点都是我做错的点,暴露出做题毛糙)。

Code:

/*ID:wwx08481PROG:barn1LANG:C++*/#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<iostream>#include<algorithm>#include<string>#include<queue>#include<stack>#include<bitset>#include<set>#include<map>#include<cctype>#include<vector>#define LL long long#define mem(f, x) memset(f, x, sizeof(f))#define See(a) cout << #a << " = " << a << endl;#define xep(i, e) for(int i = 0; i < (e); ++i)#define rep(i, s, e) for(int i = (s); i <= (e); ++i)#define drep(i, s, e) for(int i = (s); i >= (e); --i)#define debug(a, s, e) rep(_i, s, e) { cout << a[_i] << ' ';} cout << endl;#define debug2(a, s, e, ss, ee) { rep(i_, s, e) {debug(a[i_], ss, ee);}}const int MAX = 2e9;const int MIN = -2e9;const int PI = acos(-1.0);const double eps = 1e-9;using namespace std;const int N = 205;int a[N], len[N];bool cmp(int a, int b){    return a > b;}int main(){    freopen("barn1.in", "r", stdin);    freopen("barn1.out", "w", stdout);    int m, s, c;    scanf("%d%d%d", &m, &s, &c);    xep(i, c)    {        scanf("%d", &a[i]);    }    sort(a, a + c);    for(int i = 0; i < c - 1; ++i)    {        len[i] = a[i + 1] - a[i];    }    sort(len, len + c - 1, cmp);    int ans = 0;    rep(i, m - 1, c - 2)    {        ans += len[i];    }    ans += min(m, c);    printf("%d\n", ans);    return 0;}


0 0
原创粉丝点击