【求解】胜者树做【中位数】

来源:互联网 发布:淘宝怎么直播呀 编辑:程序博客网 时间:2024/05/17 06:33

中位数(mid)

Time Limit:1500MS  Memory Limit:165536K
Total Submit:3 Accepted:0

Description

有N个整数排成一行,对于第i个整数,输出前面i个数的中位数。
中位数:把数字从小到大排序后的中间数。如果是偶数个i,输出第i/2个。如:第8位,输出前8个数中的第4小的。
【输入格式】
第一行:整数 N,范围[2...100,000]
第二行:N个整数,每个整数范围[1,1,000,000,000]
【输出格式】
N个整数,每个表示前面的中位数。
【输入样例】
5
2 3 1 5 6
【输出样例】
2 2 2 2 3

Input

Output

Sample Input

Sample Output

Hint

多种方法,比如:胜者树

Source


现在的程序= =

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>

using namespace std;

int ceng=1,k=1,n,m,p,j;
bool use[444445];

struct Ttree
{
int n,son;
};
Ttree tree2[444445],tree[444445];

int _find2(int a);
int _find(int a);
void change2(int a,int b);
void change(int a,int b);
void _set();

void print()
{
for(int i=k;i<k+n;++i)
if(use[i])
cout<<"1 ";
else
cout<<"0 ";
cout<<endl;
}

void print2()
{
for(int i=1;i<k+n;++i)
cout<<tree2[i].n<<" ";
cout<<endl;
}

int main()
{
memset(tree,0,sizeof(tree));
memset(tree2,127,sizeof(tree2));

cin>>n;
while(k<n)
k*=2;

for(int i=k;i<k+n;++i)
{
_set();
cin>>p;
int ge=i-k+1;
change(i,p);
change2(i,p);
while(ge>2)
{
use[_find(1)]=false;
use[_find2(1)]=false;
change(_find(1),tree[1].n);
change(_find2(1),tree2[1].n);
ge-=2;
//print();
//print2();
/*cout<<tree2[5].son<<" ";
if(use[tree2[11].n])
cout<<"true"<<endl;
else
cout<<"false"<<endl;*/
}

int x=_find(1);
int y=_find2(1);
if(use[y])
cout<<tree2[1].n<<" ";
else
cout<<tree[1].n<<" ";

//cout<<tree[1].n<<" "<<tree2[1].n<<endl;
}

return 0;
}

void change(int a,int b)
{
//a+=k;
tree[a].n=b;
a/=2;
while(a!=0)
{
int x=_find(a*2);
if((tree[a*2].n>tree[a*2+1].n&&use[x])||!use[_find(a*2+1)])
{
//cout<<"!"<<_find(a*2)<<endl;
tree[a].son=a*2;
//cout<<tree[a].son<<"!!!"<<endl;
tree[a].n=tree[a*2].n;
}
else
{
//cout<<"!"<<_find(a*2+1)<<endl;
tree[a].son=a*2+1;
//cout<<tree[a].son<<"!!!"<<endl;
tree[a].n=tree[a*2+1].n;
}
a/=2;
}
}

void change2(int a,int b)
{
//a+=k;
tree2[a].n=b;
a/=2;
while(a!=0)
{
int x=_find2(a*2);
if((tree2[a*2].n<tree2[a*2+1].n&&use[x])||!use[_find2(a*2+1)])
{
tree2[a].son=a*2;
tree2[a].n=tree2[a*2].n;
}
else
{
tree2[a].son=a*2+1;
tree2[a].n=tree2[a*2+1].n;
}
a/=2;
}
}

int _find(int a)
{
while(tree[a].son!=a)a=tree[a].son;
return a;
}

int _find2(int a)
{
while(tree2[a].son!=a)a=tree2[a].son;
return a;
}

void _set()
{
memset(use,true,sizeof(use));
for(int i=k;i<k+n;++i)
{
tree[i].son=i;
tree2[i].son=i;
}
}


0 0
原创粉丝点击