HDU --- 4006

时间:2023-01-10 06:57:21

The kth great number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 6014    Accepted Submission(s): 2434

Problem 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
 
思路:多次更新,多次询问第K大的数,用线段树超时了,至今不知道为什么超时,最后用优先队列过的。
优先队列:
 #include<cstdio>
#include<queue>
#include<vector>
using namespace std;
struct cmp
{
bool operator()(int x, int y)
{
return x > y;
}
};
priority_queue<int, vector<int>, cmp>q;
int main(int argc, char const *argv[])
{
int n, k, temp;
char str[];
//freopen("in.c", "r", stdin);
while(~scanf("%d%d", &n, &k))
{
while(!q.empty())
q.pop();
for(int i = ;i < n;i ++)
{
scanf("%s", str);
if(str[] == 'I')
{
scanf("%d", &temp);
q.push(temp);
if(q.size() > k)
q.pop();
}
else
printf("%d\n", q.top());
}
}
return ;
}

线段树:

 #include<stdio.h>
#define MAX 1000005
typedef struct
{
int left, right, mid, num, l_cnt, r_cnt;
}NodeTree;
NodeTree node[*MAX];
void BuildTree(int k, int l, int r)
{
node[k].left = l;
node[k].right = r;
node[k].l_cnt = node[k].r_cnt = ;
node[k].mid = (l + r) >> ;
if(l == r)
return;
int mid = (l + r) >> ;
BuildTree(k << , l, mid);
BuildTree(k << |, mid+, r);
} void UpdateTree(int k, int num)
{
if(node[k].left == node[k].right)
{
node[k].num = num;
return ;
}
if(node[k].mid < num)
{
node[k].r_cnt ++;
UpdateTree(k << |, num);
}
else
{
node[k].l_cnt ++;
UpdateTree(k << , num);
}
} int GetRusult(int k, int pos)
{
if(node[k].left == node[k].right)
return node[k].num;
if(node[k].r_cnt >= pos)
GetRusult(k << |, pos);
else
GetRusult(k << , pos - node[k].r_cnt);
} int main(int argc, char const *argv[])
{
int n, k, a, i;
char str[];
//freopen("in.c", "r", stdin);
while(~scanf("%d%d", &n, &k))
{
BuildTree(, , n);
for(i = ;i < n;i ++)
{
scanf("%s", str);
if(str[] == 'I')
{
scanf("%d%d", &a);
UpdateTree(, a);
}
else
{
printf("%d\n", GetRusult(, k));
}
}
}
return ;
}