【二分答案】SDUT 3916 上色的纱雾

xiaoxiao2021-02-28  126

Problem Description

输入n,m分别代表,n代表需要上色的n个点的一维下标,m代表你当前拥有的画笔数量。问你把所有点画完最少需要的时间,画笔同时移动一个单位需要一秒。

Example Input

3 2 1 4 8 3 1 1 2 9 4 2 1 2 3 6

Example Output

3 8 2

Hint

两支画笔,第一支画笔初始地点选择 1,第二支画笔初始地点选择地点 8。 那么 3s 后第一支画笔可以到达地点 4,这样 3 个点就可以全部涂上了。

代码:二分枚举答案,不断更新最小答案

#include<bits/stdc++.h> using namespace std; int a[100055], n, m; int judge(int ans)//判断该答案是否满足要求 { int make = a[0] + ans, num = 1;//假设一笔画ans长度 for(int i = 0; i < n; i++) { if(make < a[i]) { num++;//多加一笔 make = a[i] + ans;//更新当前能画的最远距离 } } return num <= m;//满足返回1,否则0 } void solve() { int l = 0, r = 1000000000, ans; for(int i=0; i<150; i++)//枚举次数的差不多边界情况。也可以while(l <= r) { int mid = (l + r) / 2; if(judge(mid))//满足 { ans = mid;//更新答案 r = mid-1;//减小画的长度 } else l = mid + 1;//增加画的长度 } printf("%d\n", ans);//退出循环,输出答案 } int main() { while(~scanf("%d %d", &n, &m)) { for(int i = 0; i < n; i++) scanf("%d", &a[i]); sort(a, a +n);//从小到大排序 solve(); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-39800.html

最新回复(0)