题意:在一个一维空间里有若干人然后要找一个地方聚在一起然后每个人移动有花费,问你在哪里花费最小?
思路:很典型的三分问题了,一开始以为是一道java题没想到用double 就可以了。
代码如下:
1 /************************************************** 2 * Author : xiaohao Z 3 * Blog : http://www.cnblogs.com/shu-xiaohao/ 4 * Last modified : 2014-05-11 16:53 5 * Filename : F.cpp 6 * Description : 7 * ************************************************/ 8 9 #include <iostream> 10 #include <cstdio> 11 #include <cstring> 12 #include <cstdlib> 13 #include <cmath> 14 #include <algorithm> 15 #include <queue> 16 #include <stack> 17 #include <vector> 18 #include <set> 19 #include <map> 20 #define MP(a, b) make_pair(a, b) 21 #define PB(a) push_back(a) 22 23 using namespace std; 24 typedef long long ll; 25 typedef pair<int, int> pii; 26 typedef pair<unsigned int,unsigned int> puu; 27 typedef pair<int, double> pid; 28 typedef pair<ll, int> pli; 29 typedef pair<int, ll> pil; 30 31 const int INF = 0x3f3f3f3f; 32 const double eps = 1E-6; 33 const int LEN = 100000+10; 34 double pos[LEN], w[LEN]; 35 int n; 36 37 double calc(double p){ 38 double ret = 0; 39 for(int i=0; i<n; i++){ 40 ret += (abs(pos[i]-p)*abs(pos[i]-p)*abs(pos[i]-p)*w[i]); 41 } 42 return ret; 43 } 44 45 int main() 46 { 47 // freopen("in.txt", "r", stdin); 48 49 int T, kase = 1; 50 scanf("%d", &T); 51 while(T--){ 52 scanf("%d", &n); 53 double r = -1000000, l = 1000000; 54 for(int i=0; i<n; i++){ 55 scanf("%lf%lf", &pos[i], &w[i]); 56 l = min(l, pos[i]); 57 r = max(r, pos[i]); 58 } 59 while(fabs(r-l)>eps){ 60 double mid = (l+r)/2, midmid = (mid+r)/2, d1, d2; 61 d1 = calc(mid); 62 d2 = calc(midmid); 63 if(d1+eps < d2) r = midmid; 64 else l = mid; 65 } 66 double ans = calc(l); 67 printf("Case #%d: ", kase ++); 68 printf("%.0lf ", ans); 69 } 70 return 0; 71 }