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;
}
思路:见附件,从概率的角度证明了这个数一定是中位数,如果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;
}
相关文章推荐
- uva 10057 A mid-summer night's dreamk
- uva 10057 A mid-summer night’s dream 夏天晚上的梦
- uva - 10057 - A mid-summer night's dream. (数学、中位数)
- UVA 10057 A mid-summer night's dream. 仲夏夜之梦 求中位数
- UVA - 10057 - A mid-summer night's dream. (找中位数!)
- UVA - 10057 A mid-summer night's dream.
- uva 10057 A mid-summer night's dreamk
- UVA - 10057 A mid-summer night's dream.
- UVa 10057 - A mid-summer night's dream.
- UVA 10057 - A mid-summer night's dream.
- uva 10057 - A mid-summer night's dream.
- uva 10057 A mid-summer night's dream.
- UVa:10057 A mid-summer night's dream
- uva10057 A mid-summer night's dream.
- UVA10057-A mid-summer night's dream.
- UVA - 10057 A mid-summer night's dream.
- UVA 10057 A mid-summer night's dream. 仲夏夜之梦 求中位数
- UVa 10057 - A mid-summer night's dream.
- UVa 10057 - A mid-summer night's dream.
- A mid-summer night’s dream - UVa 10057 中位数