题意:n个数,n<=500,问最少添加多少个数能使得X为中位数
vector暴力添加x后排序,无论当前中位数小于还是大于x 添加x总能使当前中位数接近x 复杂度O(n^2logn)
#include <bits/stdc++.h>
using namespace std;
const int N=2e3+20;
vector<int> a;
int main()
{
int n,x;
while(cin>>n>>x)
{
for(int i=0;i<n;i++)
{
int b;
cin>>b;
a.push_back(b);
}
sort(a.begin(),a.end());
int m=(n+1)/2,ans=0;
m--;//0开始编号
while(a[m]!=x) //n<=500 最多添加500个元素
{
//无论当前中位数小于还是大于x 添加x总能使当前中位数接近x
a.push_back(x);
sort(a.begin(),a.end());
m=(a.size()+1)/2;
m--;
ans++;
}
cout<<ans<<endl;
a.clear();
}
return 0;
}

本文介绍了一种通过不断添加指定数值直至达到目标中位数的算法。该方法适用于小规模数据集,通过逐步增加目标值并重新排序来调整中位数。

174

被折叠的 条评论
为什么被折叠?



