BZOJ 3110 K大数查询
Description
有\(N\)个位置,\(M\)个操作。操作有两种,每次操作如果是\(1\;a\;b\;c\)的形式表示在第\(a\)个位置到第\(b\)个位置,每个位置加入一个数\(c\)如果是\(2\;a\;b\;c\)形式,表示询问从第\(a\)个位置到第\(b\)个位置,第\(c\)大的数是多少。
Input
第一行\(N,M\)
接下来\(M\)行,每行形如\(1\;a\;b\;c\)或\(2\;a\;b\;c\)。
Output
输出每个询问的结果
Sample Input
2 5
1 1 2 1
1 1 2 2
2 1 1 2
2 1 1 1
2 1 2 3
Sample Output
1
2
1
HINT
\(N,M \le 50000,N,M \le 50000\)
\(a \le b \le N\)
\(1\)操作中\(abs(c) \le N\)
\(2\)操作中\(abs(c) \le 2^{31}-1\)
这题肯定有经典的树套树做法(我没写),下面讲整体二分的做法。
我们将修改与询问一起整体二分。每次查询rank采用树状数组(线段树)。
区间修改、区间查询的两个树状数组实现。用\(B\)表示差分数组,\(P\)表示每个点的值,则
\[P_{n}=\sum_{i=1}^{n}B_{i}
\]
\[sum = \sum_{i=1}^{n}P_{i}=\sum_{i=1}^{n} \sum_{j=1}^{i}B_{i}=\sum_{i=1}^{n}(n-i+1)B_{i}=n \times \sum_{i=1}^{n}B_{i}-\sum_{i=1}^{n}(i-1)B_{i}
\]
于是皆大欢喜。
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define maxn (50010)
int n,m,ans[maxn],tree1[maxn],tree2[maxn],task,tadj; bool is[maxn];
struct node
{
int a,b,c,id; bool sign;
inline void read(int i,bool s) { sign = s; id = i; scanf("%d %d %d",&a,&b,&c); }
friend inline bool operator <(const node &a,const node &b) { return a.id < b.id; }
}ask[maxn],adj[maxn],tmp[maxn];
inline bool cmp(const node &a,const node &b) { return a.c == b.c?a.id < b.id:a.c > b.c; }
inline int lowbit(int a) { return a&-a; }
inline void ins(int *tree,int a,int b) { for (;a<=n;a += lowbit(a)) tree[a] += b; }
inline int sum(int *tree,int a) { int ret = 0; for (;a;a -= lowbit(a)) ret += tree[a]; return ret; }
inline void ready()
{
for (int i = 1,opt;i <= m;++i)
{
scanf("%d",&opt); opt--;
if (opt) ask[++task].read(i,opt),is[i] = true; else adj[++tadj].read(i,opt);
}
sort(adj+1,adj+tadj+1,cmp);
}
inline void calc(int lask,int rask,int ladj,int radj,int &ll,int &rr)
{
int tot = 0;
for (int i = lask;i <= rask;++i) tmp[++tot] = ask[i];
for (int i = ladj;i <= radj;++i) tmp[++tot] = adj[i];
sort(tmp+1,tmp+tot+1);
for (int i = 1;i <= tot;++i)
{
if (!tmp[i].sign)
{
ins(tree1,tmp[i].a,1); ins(tree1,tmp[i].b+1,-1);
ins(tree2,tmp[i].a,tmp[i].a-1); ins(tree2,tmp[i].b+1,-tmp[i].b);
}
else
{
int rank = (sum(tree1,tmp[i].b)*tmp[i].b-sum(tree2,tmp[i].b))-(sum(tree1,tmp[i].a-1)*(tmp[i].a-1)-sum(tree2,tmp[i].a-1));
if (rank >= tmp[i].c) ask[++ll] = tmp[i];
else tmp[i].c -= rank,ask[--rr] = tmp[i];
}
}
for (int i = ladj;i <= radj;++i)
{
ins(tree1,adj[i].a,-1); ins(tree1,adj[i].b+1,1);
ins(tree2,adj[i].a,1-adj[i].a); ins(tree2,adj[i].b+1,adj[i].b);
}
}
inline void work(int lask,int rask,int ladj,int radj)
{
if (lask > rask) return;
if (ladj == radj)
{
for (int i = lask;i <= rask;++i) ans[ask[i].id] = adj[ladj].c;
return;
}
int ll = lask-1,rr = rask+1,mid = (ladj+radj)>>1;
calc(lask,rask,ladj,mid,ll,rr);
work(lask,ll,ladj,mid);
work(rr,rask,mid+1,radj);
}
int main()
{
freopen("3110.in","r",stdin);
freopen("3110.out","w",stdout);
scanf("%d %d",&n,&m);
ready();
work(1,task,1,tadj);
for (int i = 1;i <= m;++i) if (is[i]) printf("%d\n",ans[i]);
fclose(stdin); fclose(stdout);
return 0;
}
高考结束,重新回归。