您的位置:首页 > 其它

UVA 10057 A mid-summer night's dream.

2012-10-16 21:52 387 查看
大意: 给定一串 (|X1-A| + |X2-A| + … … + |Xn-A|) ,让你求一个值A使得此表达式最小。

思路:见附件,从概率的角度证明了这个数一定是中位数,如果n是奇数,A一定只有一个,否则可以取a[q],a[q+1]闭区间之间的任何数。

关于中位数定理的一个概率证明(点击下载附件)

CODE:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

#define MAXN 1000010

int a[MAXN];

int main()
{
int n;
int tot1, tot2;
while(~scanf("%d", &n))
{
tot1 = tot2 = 0;
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
sort(a, a+n);
int q = (n-1)/2;
if(n & 1) //奇数
{
for(int i = q+1; i < n ; i++)
{
if(a[i] == a[q]) tot1++;
}
for(int i = q-1; i >= 0; i--)
{
if(a[i] == a[q]) tot1++;
}
tot1++; //别漏了中位数
}
else
{
for(int i = q+2; i < n; i++)
{
if(a[i] == a[q+1]) tot1++;
}
for(int i = q-1; i >= 0; i--)
{
if(a[i] == a[q]) tot1++;
}
tot1 += 2; //区间两端都要加上
}
if(n & 1) tot2 = 1;
else tot2 = a[q+1]-a[q]+1;
printf("%d %d %d\n", a[q], tot1, tot2); //中位数,与A的值相等的数,所有满足最小值的数。
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: