[Whole half] Luogu P1527 [National Team] matrix multiplication

To a N * N matrix, repeatedly asked the sub-matrix of small K

 

Whole dichotomy of the classic title.

Individual interrogation obviously be bipartite, with maintaining the size of the tree sub-matrix array <= mid  counted number of.

A plurality of interrogation put them at the same time two minutes, the answer <= mid  interrogation thrown left, > MID  thrown into the right side of recursive processing.

Half the time directly within the matrix of numbers in half.

Time complexity is half for each layer, the maximum number is added to each array a tree, each query can be processed at most once, a total of log N  layer.

The time complexity is O ((N 2 + Q) log . 3 N), and some small details embodied in the code tips.

 1 #include<bits/stdc++.h>
 2 #define rep(i,a,b) for(register int i=a;i<=b;++i)
 3 #define rpd(i,a,b) for(register int i=a;i>=b;--i)
 4 #define rep1(i,x) for(register int i=head[x];i;i=nxt[i])
 5 typedef long long ll;
 6 const int N=500+5,Q=60000+5;
 7 using namespace std;
 8 inline int read(){
 9     int x=0,f=1;char ch=getchar();
10     while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
11     while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
12     return x*f;
13 }
14 int n,q,m;int t1[Q],t2[Q],ans[Q],id[Q],C[N][N];
15 int lowbit(int x){return x&(-x);}
16 void add(int x,int y,int opt){for(int i=x;i<=n;i+=lowbit(i))for(int j=y;j<=n;j+=lowbit(j))C[i][j]+=opt;}
17 int find(int x,int y){int sum=0;for(int i=x;i;i-=lowbit(i))for(int j=y;j;j-=lowbit(j))sum+=C[i][j];return sum;}
18 int ask(int x,int y,int xx,int yy){return find(xx,yy)-find(xx,y-1)-find(x-1,yy)+find(x-1,y-1);}
19 struct Matrix{int i,j,x;}t[N*N];
20 bool cmp(Matrix i,Matrix j){return i.x<j.x;}
21 struct Query{int x,y,xx,yy,k;}a[Q];
22 void work(int l,int r,int L,int R){
23     if(L>R)return;
24     if(l==r){rep(i,L,R)ans[id[i]]=t[l].x;return;}
25     int mid=l+r>>1,cnt1=0,cnt2=0;
26     rep(i,l,mid)add(t[i].i,t[i].j,1);
27     rep(i,L,R){
28         int now=id[i],nowk=ask(a[now].x,a[now].y,a[now].xx,a[now].yy);
29         if(nowk>=a[now].k)t1[++cnt1]=now;
30         else t2[++cnt2]=now,a[now].k-=nowk;
31     }
32     int nowl=L-1;
33     rep(i,1,cnt1)id[++nowl]=t1[i];
34     rep(i,1,cnt2)id[++nowl]=t2[i];
35     rep(i,l,mid)add(t[i].i,t[i].j,-1);
36     work(l,mid,L,L+cnt1-1);
37     work(mid+1,r,L+cnt1,R);
38 }
39 int main(){
40     n=read();q=read();
41     rep(i,1,n)rep(j,1,n)t[++m]=(Matrix){i,j,read()};
42     sort(t+1,t+m+1,cmp);
43     rep(i,1,q)a[i]=(Query){read(),read(),read(),read(),read()};
44     rep(i,1,q)id[i]=i;work(1,m,1,q);
45     rep(i,1,q)printf("%d\n",ans[i]);
46     //system("pause");
47     return 0;
48 }
View Code

 

Guess you like

Origin www.cnblogs.com/maximumhanyu/p/11423676.html