二分查找(中位数)
传送门(洛谷)
题目描述:
此题stl大法万岁,一个vector消掉所有
但找中位数我们需要对当前数列进行排序,但是我们如果每次插入一个数就排一次序,那么无论是sort还是冒泡神仙都会超时,因此我们又想到了一个方法:
二分!!!!!!!
其余讲解在代码上:
#include<bits/stdc++.h>
#include<vector>
using namespace std;
vector <int> a;
int n;
template <class t> void read(t &x)//读入优化
{
x=0;int f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)){x=10*x+ch-'0';ch=getchar();}
x*=f;
}
void readdata()
{
read(n);
for(int i=1;i<=n;i++)
{
int x;
read(x);
a.insert(upper_bound(a.begin(),a.end(),x),x);//为了保证每次插入都是有序的,我们用一个upper_bound进行排序
if(i%2==1)//根据题目,是奇数就进行一次输出
{
printf("%d\n",a[(i-1)/2]);//vector是从0开始储存的
}
}
}
void work()
{
}
int main()
{
freopen("input.txt","r",stdin);
readdata();
work();
return 0;
}