hdu 1551 恶心的卡精度题

此题巨恶心,花了我好几天才过掉……

首先是题目巨难懂,我是读了一个多小时才差不多明白的。读懂题意后马上想到用二分查找,代码打出来了,却死活过不了。几天以后,终于在北大讨论版看到有人说,只要输入的时候+0.005再转成整数就不会丢失精度了,泪流满面啊……

/*
* hdu1551/win.cpp
* Created on: 2011-11-15
* Author : ben
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <functional>
#include <numeric>
#include <cctype>
using namespace std;
const int MAXN = 10100;
typedef long long typec;
typec cables[MAXN];
int N, K;

bool judge(typec ans) {
typec k = 0;
for (int i = 0; i < N; i++) {
k += cables[i] / ans;
}
if (k >= K) {
return true;
}
return false;
}

int solve(typec high) {
typec low = 1, mid;
typec ans = 0;
while (low <= high) {
mid = (low + high) / 2;
if (judge(mid)) {
low = mid + 1;
ans = mid;
} else {
high = mid - 1;
}
}
return ans;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
while (scanf("%d%d", &N, &K) == 2) {
if (N == 0 && K == 0) {
break;
}
typec total = 0;
double temp;
for (int i = 0; i < N; i++) {
scanf("%lf", &temp);
temp += 0.005;//此题过与不过的核心
cables[i] = (typec) (temp * 100);
total += cables[i];
}
typec ans = solve((typec) (total / K));
printf("%.2f\n", ans / 100.0);
}
return 0;
}



原文地址:https://www.cnblogs.com/moonbay/p/2254202.html