hihocoder-Week216-Gas Stations

hihocoder-Week216-Gas Stations

 

题目1 : Gas Stations

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

There are N gas stations on a straight, M kilo-meters long highway. The i-th gas station is Ai kilo-meters away from the beginning of the highway. (It is guaruanteed that there is one gas station at each end of the highway)

Now the mayor can build K more gas stations. He wants to minimize the maximum distance between two adjacent gas station. Can you help him?

输入

The first line contains 3 integer N, M, k. (2 <= N <= 1000, 1 <= M, K <= 100000)  

The second line contains N integer, A1, A2, ... AN. (0 = A1 <= A2 <= ... <= AN = M)

输出

The minimized maximum distance rounded to one decimal place.

样例输入
3 10 2  
0 2 10
样例输出
2.7

 

 

使用二分法进行解决:

  注意: 在停止条件那里,第一次设置的是小于等于0.1,发现不能通过所有答案,需要再降低一点精度,0.01。  

 

 

#include <cstdio> 

const int MAXN = 1000 + 10; 
int n, m ,k, num[MAXN]; 
float ans; 

void find_target(float begin, float end)
{
	if(end - begin < 0.01)
	{
		ans = end; 
		return; 
	}
	float inv = begin + (end - begin)/2, pre = num[0];  
	int i = 0, cnt =0, flag = 1; 
	while(i+1<n)
	{
		if(cnt > k){
			flag = 0;  
			break; 
		} 
		if((num[i+1] - pre) <= inv)
		{
			pre = num[i+1]; 
			i++; 
		}else{
			pre = pre + inv; 
			cnt++; 
		} 
	} 
	if(flag)
	{
		find_target(begin, inv); 
	}else{
		find_target(inv, end); 
	}
}


int main(){ 
	while(scanf("%d %d %d", &n, &m, &k) != EOF)
	{
		for(int i=0; i<n; ++i)
		{
			scanf("%d", &num[i]); 
		}
		ans = m;  
		find_target(0, m); 
		printf("%.1f\n", ans);
	}
	return 0; 
} 

  

 

posted @ 2018-08-25 19:45  zhang--yd  阅读(210)  评论(0编辑  收藏  举报