这道题让我对线段树的使用有了一个新的认识,它可以支持修改地以nlongn的复杂度在线查询排在第几的数是谁
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 500005
using namespace std;
int n, k, f[N];
struct aa{
int num;
char s[15];
}a[N];
struct node{
int l, r, v;
}tree[N * 4];
void build(int l, int r, int t){
tree[t].l = l;
tree[t].r = r;
tree[t].v = r - l + 1;
if(l != r){
int mid = (l + r)>>1;
build(l, mid, t + t);
build(mid + 1, r, t + t + 1);
}
}
int ask(int v, int t){
tree[t].v --;
if(tree[t].l == tree[t].r){
return tree[t].l;
}
if(v > tree[t + t].v)return ask(v - tree[t + t].v, t + t + 1);
else return ask(v, t + t);
}
int main()
{
int k = (int)sqrt(N * 1.0);
for(int i = 1; i <= k; i ++){
for(int j = i + 1; i * j < N; j ++)
f[i * j] += 2;
f[i * i] ++;
}
while(scanf("%d%d", &n, &k) != EOF){
build(0, n - 1, 1);
for(int i = 0; i < n; i ++)scanf("%s %d", a[i].s, &a[i].num);
int cnt = 1, pos, &num = tree[1].v, imax = 0, ans;
while(num){
pos = ask(k, 1);
if(imax < f[cnt]){ans = pos; imax = f[cnt];}
cnt ++;
if(num == 0)break;
if(a[pos].num > 0)k = (k - 2 + a[pos].num)%num + 1;
else k = ((k - 1 + a[pos].num) % num + num) % num + 1;
}printf("%s %d\n", a[ans].s, imax);
}
return 0;
}