*【SGU - 114】Telecasting station (带权中位数 或 三分)
題干:
Every city in Berland is situated on Ox axis. The government of the country decided to build new telecasting station. After many experiments Berland scientists came to a conclusion that in any city citizens?displeasure?is equal to product of citizens amount in it by distance between city and TV-station. Find such point on Ox axis for station so that sum of?displeasures?of all cities is minimal.
?
Input
Input begins from line with integer positive number?N?(0<N<15000)?– amount of cities in Berland. Following?N?pairs?(X,?P)?describes cities?(0<X, P<50000), where?X?is a coordinate of city and?P?is an amount of citizens. All numbers separated by whitespace(s).
?
Output
Write the best position for TV-station with accuracy?10-5.
?
Sample Input
4 1 3 2 1 5 2 6 2?
Sample Output
3.00000題目大意:
n個城市,第i個城市坐標為x[i],人口為p[i],現在要建立一個電視臺,使得各個城市到電視臺的距離乘以該城市人口之和最小。
解題報告:
可以這樣來簡單考慮:若各個城市人口均為1,則問題就是求城市坐標的中位數。現在人口為p,則可以看做是有p個人口為1的城市,這樣就把問題轉化為求中位數。
AC代碼:
#include <iostream> #include<cstdio> #include<cmath> #include<cstring> #include<map> #include<algorithm> using namespace std; #define LL long long struct city {double x,p; }c[50005]; bool cmp(city a,city b) {return a.x<=b.x; } int main() {int n;scanf("%d",&n);double sum=0.0;for(int i=0;i<n;++i){scanf("%lf%lf",&c[i].x,&c[i].p);sum+=c[i].p;}double s=0.0;sort(c,c+n,cmp);for(int i=0;i<n;++i){s+=c[i].p;if(s-sum/2>=1e-10) {printf("%.10lf\n",c[i].x);break;}}return 0; }三分的代碼:(但是怎么能保證都是整數呢?題目爬去不到了,,也交不了試試)
#include <bits/stdc++.h> #define max(a,b) ((a)>(b))?(a):(b) #define min(a,b) ((a)>(b))?(b):(a) #define rep(i,initial_n,end_n) for(int (i)=(initial_n);(i)<(end_n);i++) #define repp(i,initial_n,end_n) for(int (i)=(initial_n);(i)<=(end_n);(i)++) #define eps 1.0E-8 #define MAX_N 1010 #define INF 1 << 30 using namespace std; typedef pair<int, int> pii; typedef pair<double, double> pdd; typedef long long ll; typedef unsigned long long ull;pii a[15010];int main() {int n;scanf("%d", &n);int minn = INT_MAX, maxx = INT_MIN;rep(i, 0, n) {scanf("%d%d", &a[i].first, &a[i].second);if(minn > a[i].first) minn = a[i].first;if(maxx < a[i].first) maxx = a[i].first;}double b = minn, e = maxx, m = (b+e)/2, mm = (m+e)/2;while(b - e < -eps) {double tmp = 0, tmpp = 0;rep(i, 0, n) {tmp += fabs(a[i].first - m) * 1.0 * a[i].second, tmpp += fabs(a[i].first - mm) * 1.0 * a[i].second;}if(tmp - tmpp < -eps) e = mm;else b = m;m = (b+e)/2, mm = (m+e)/2;}printf("%f\n", m);return 0;}?
總結
以上是生活随笔為你收集整理的*【SGU - 114】Telecasting station (带权中位数 或 三分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【牛客 - 315B】 勇气获得机(二叉
- 下一篇: sniffer.exe - sniffe