题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1248
The kth great number
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submit: 107(36 users) Total Accepted: 64(35 users) Rating: Special Judge: No
Description
Xiao Ming and Xiao Bao are playing a simple Numbers game. In a round Xiao Ming can choose to write down a number, or ask Xiao Bao what the kth great number is. Because the number written by Xiao Ming is too much, Xiao Bao is feeling giddy. Now, try to help Xiao Bao.
Input
There are several test cases. For each test case, the first line of input contains two positive integer n, k. Then n lines follow. If Xiao Ming choose to write down a number, there will be an ” I” followed by a number that Xiao Ming will write down. If Xiao Ming choose to ask Xiao Bao, there will be a “Q”, then you need to output the kth great number.
Output
The output consists of one integer representing the largest number of islands that all lie on one line.
Sample Input
8 3
I 1
I 2
I 3
Q
I 5
Q
I 4
Q
Sample Output
1
2
3
Source
The 36th ACM/ICPC Asia Regional Dalian Site —— Online Contest
【中文题意】每一个I是向原序列中插入一个数的意思,每一个Q是找出序列中的第K大数是几。
【思路分析】先用线段树建树,树上的每一个点代表一个数,然后不断进行更新和查找就OK了。
【AC代码】
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 100000
struct node
{
int left,right,val;
} c[maxn*8];
void build_tree(int l,int r,int root)
{
c[root].left=l;
c[root].right=r;
if(l==r)
{
c[root].val=0;
return ;
}
int mid=(l+r)/2;
build_tree(l,mid,root*2);
build_tree(mid+1,r,root*2+1);
c[root].val=0;
}
void update_tree(int root,int pos)
{
if(c[root].left==c[root].right)
{
if(c[root].left==pos)
{
c[root].val++;
}
return ;
}
int mid=(c[root].left+c[root].right)/2;
if(pos<=mid)
{
update_tree(root*2,pos);
}
else
{
update_tree(root*2+1,pos);
}
c[root].val=c[root*2].val+c[root*2+1].val;
}
int query(int root,int k)
{
if(k>c[root*2+1].val)
{
if(c[root].left==c[root].right)
{
return c[root].left;
}
query(root*2,k-c[root*2+1].val);
}
else
{
query(root*2+1,k);
}
}
int main()
{
int n,k,a;
char str[5];
while(~scanf("%d%d",&n,&k))
{
build_tree(1,maxn,1);
for(int i=0; i<n; i++)
{
scanf("%s",str);
if(str[0]=='I')
{
scanf("%d",&a);
update_tree(1,a);
}
else if(str[0]=='Q')
{
printf("%d\n",query(1,k));
}
}
}
return 0;
}