poj1064http://poj.org/problem?id=1064
浮点数最好不要设ub-lb>eps,不好掌握。注意printf(%.2lf",...)是四舍五入,这里不行所以要先取证floor
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cstdlib> 6 #include<cmath> 7 #define lson l, m, rt<<1 8 #define rson m+1, r, rt<<1|1 9 #define IO ios::sync_with_stdio(false);cin.tie(0); 10 #define INF 1e9 11 #define MAXN 10010 12 const int MOD=1e9+7; 13 typedef long long ll; 14 using namespace std; 15 int n, k; 16 double a[MAXN]; 17 int C(double x) 18 { 19 int num = 0; 20 for(int i = 0; i < n; i++){ 21 num += (int)(a[i]/x); 22 } 23 return num >= k; 24 } 25 void solve() 26 { 27 double lb=0, ub=INF; 28 for(int i = 0; i < 100; i++){//这里限定次数而不是限定ub-lb>EPS,因为EPS设置不好会陷入死循环 29 double mid = (lb+ub)/2; 30 if(C(mid)){//左闭右开 31 lb = mid; 32 } 33 else ub = mid; 34 } 35 printf("%.2lf ", floor(lb*100)/100);//floor是向下取整,但似乎返回的还是原类型(这里即double),如果直接输出ub则是四舍五入 36 } 37 int main() 38 { 39 IO; 40 cin >> n >> k; 41 for(int i = 0; i < n; i++){ 42 cin >> a[i]; 43 } 44 solve(); 45 return 0; 46 }
poj2456http://poj.org/problem?id=2456
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cstdlib> 6 #include<cmath> 7 #define lson l, m, rt<<1 8 #define rson m+1, r, rt<<1|1 9 #define IO ios::sync_with_stdio(false);cin.tie(0); 10 #define INF 1e9 11 #define MAXN 10010 12 const int MOD=1e9+7; 13 typedef long long ll; 14 using namespace std; 15 int n, m, a[100010]; 16 int C(int x) 17 { 18 int crt=0, last=0; 19 for(int i = 1; i < m; i++){//注意这里因为默认第一头奶牛放在第一个牛舍,所以计数从1开始 20 crt=last+1; 21 while(crt<n&&a[crt]-a[last]<x){ 22 crt++; 23 } 24 last=crt; 25 if(crt==n) return 0; 26 } 27 return 1; 28 } 29 void solve() 30 { 31 sort(a, a+n); 32 int lb=0, ub=INF; 33 while(ub-lb>1){ 34 int mid = (lb+ub)>>1; 35 if(C(mid)){//左闭右开 36 lb = mid; 37 } 38 else ub = mid; 39 } 40 cout << lb << endl; 41 } 42 int main() 43 { 44 cin >> n >> m; 45 for(int i = 0; i < n; i++){ 46 cin >> a[i]; 47 } 48 solve(); 49 return 0; 50 }