Code Forces68B
题意:给定n个数,他们之间可以互相传递一定的值,每次传递有k%的损失,现在需要进行若干次传递使得最终每个数都等于所有数的均值。
做法:设置两个量maxn和minn,不断地更新maxn和minn,直到两者相等。中间借助mid = (maxn+minn)/2进行比较。
代码:
#include <stdio.h> #include <iostream> using namespace std; const int MAXN = 10000 + 5; const double eps = 1e-6; double a[MAXN]; int main(){ // freopen("in.txt", "r", stdin); int n, k, i; cin >> n >> k; double maxn = 0, minn = 1000; for(i=0; i<n; i++){ cin >> a[i]; if(minn>a[i]) minn = a[i]; maxn += a[i]; } maxn /= n; while(maxn-minn>eps){ double jar = 0; double mid = (maxn+minn)/2; for(i=0; i<n; i++){ if(a[i]>mid) jar += (a[i]-mid)*(1-k/100.0); else jar -= (mid - a[i]); } if(jar>0) minn = mid; else maxn = mid; } cout.precision(9); cout << fixed << maxn << endl; }
Greatness is never a given, it must be earned.