1. 程式人生 > >跳石頭與二分法

跳石頭與二分法

vid UC -s while opened OS like between spa

題目描述

5G is the proposed next telecommunications standards beyond the current 4G standards. 5G planning aims at higher capacity than current 4G, allowing a higher density of mobile broadband users, and supporting device-to- device, reliable, and massive wireless communications. A telecommunication company would like to install more base stations to provide better communication for customers. Due to the installation cost and available locations,the company can only install S (2 ≤ S ≤ L) base stations at L (2 ≤ L ≤ 100, 000) candidate locations. Since the base stations work in the same frequency band, they will interfere and cause severe performance degradation. To provide high quality communication experience to customers, the company would like to maximize the distance between the base stations so as to reduce the wireless interference among the base stations. Suppose the L candidate locations are in a straight line at locations P1, P2,..., PL (0 ≤ Pi ≤ 1, 000, 000) and the company wants to install S base stations at the L candidate locations. What is the largest minimum distance among the S base stations?

輸入

The input data includes multiple test sets.
Each set starts with a line which specifies L (i.e., the number of candidate locations) and S (i.e., the number of base stations). The next line contains L space-separated integers which represent P1, P2,..., PL.
The input data ends “0 0”.

輸出

For each set, you need to output a single line which should be the largest minimum distance among the base stations.

樣例輸入

5 3  
2 3 9 6 11
4 3  
1 4 9 10
0 0  

樣例輸出

4
3

提示

For the first set, the 3 base stations can be installed at locations 2, 6, 11.

這題雖然不是跳石頭,但可以用那種方法做 即讓最小的兩個點距離最大

技術分享圖片
 1 #include <iostream>
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 int a[100005]={0};
 5 int n;
 6 bool fun(int x,int total)
7 { 8 int i=0; 9 int cnt=-1; 10 int now=0; 11 while(i<n) 12 { 13 if(a[i]-a[now]<x) 14 { 15 cnt++; 16 } 17 else 18 { 19 now=i; 20 } 21 i++; 22 } 23 if(cnt<=total) return true; 24 return false; 25 } 26 int main() 27 { 28 int m,i; 29 while(~scanf("%d%d",&n,&m)&&n&&m) 30 { 31 int x=n-m; 32 int ans=-1; 33 memset(a,0,sizeof(a)); 34 for(i=0;i<n;i++) 35 { 36 scanf("%d",&a[i]); 37 } 38 sort(a,a+n); 39 int mid; 40 int l=0,r=1000000; 41 while(l<r) 42 { 43 mid=(l+r)/2; 44 if(fun(mid,x)) 45 { 46 ans=mid; 47 l=mid+1; 48 } 49 else 50 { 51 r=mid; 52 } 53 } 54 printf("%d\n",ans); 55 } 56 return 0; 57 }
隊友的代碼

坑了隊友一把 跟他說優化那個r和l

這道題我做過但不熟悉,要自己練 書上有二分法的代碼

跳石頭與二分法