1. 程式人生 > >Cideforces 1093E Intersection of Permutations (CDQ分治+樹狀數組)

Cideforces 1093E Intersection of Permutations (CDQ分治+樹狀數組)

ide class 建立 div 操作類 esp 多少 很多 con

---恢復內容開始---

題意:給你兩個數組a和b,a,b都是一個n的全排列;有兩種操作:一種是詢問區間在數組a的區間[l1,r1]和數組b的區間[l2,r2]出現了多少相同的數字,另一種是交換數組b中x位置和y位置的數字。

思路:我們可以建立數組b對數組a的映射mp,mp[x]表示數組b中x位置的數在數組a中出現的位置,這樣問題轉化為了帶修改的詢問一個矩形內點的個數的問題。想法是樹套樹,但是這題卡常,很多樹套樹會被卡掉,介於本辣雞的代碼能力,很容易寫醜,所以用CDQ分治。

此問題和三維偏序問題很像(把每個操作的時間看作一維)。

代碼的實現參考了這篇博客:http://www.cnblogs.com/mlystdcall/p/6219421.html

代碼:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=200010;

struct Query{
	int type,x,y,flag,num,cnt;//操作類型,x,y,+還是-,第幾個詢問
	bool operator <(const Query& rhs)const{
		return x==rhs.x?type<rhs.type:x<rhs.x;
	} 
}; 

Query query[maxn*10],tmp[maxn*10];
int tot=0,ans[maxn],a[maxn],b[maxn],p[maxn],mp[maxn],n,m;

namespace BIT{
	int c[maxn];
	inline int lowbit(int x){
		return x&(-x);
	}
	int ask(int x){
		int ans=0;
		for(;x;x-=lowbit(x))ans+=c[x];
		return ans;
	}
	void add(int x,int y){
		for(;x<=n;x+=lowbit(x))c[x]+=y;
	}
	void clear(int x){
		for(;x<=n;x+=lowbit(x)){
			if(c[x])c[x]=0;
			else break;
		}
	}
}

void cdq(int L,int R){
	if(R==L)return;
	int M=(L+R)>>1;
	cdq(L,M);
	cdq(M+1,R);
	int l=L,r=M+1;
	int o=L;
	while(l<=M&&r<=R){
		if(query[l]<query[r]){
			if(query[l].type==0)
				BIT::add(query[l].y,query[l].cnt);
			tmp[o++]=query[l++];
		}
		else{
			if(query[r].type==1)
				ans[query[r].num]+=query[r].flag*BIT::ask(query[r].y);
			tmp[o++]=query[r++];
		}
	}
	while(l<=M)
		tmp[o++]=query[l++];
	while(r<=R){
		if(query[r].type==1)
			ans[query[r].num]+=query[r].flag*BIT::ask(query[r].y);
		tmp[o++]=query[r++];
	}
	for(int i=L;i<=R;i++){
		BIT::clear(tmp[i].y);
		query[i]=tmp[i];
	}
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		p[a[i]]=i;
	}
	for(int i=1;i<=n;i++){
		scanf("%d",&b[i]);
		mp[i]=p[b[i]];
		query[++tot]=(Query){0,i,mp[i],0,0,1};
	}
	int cnt=0;
	for(int i=1;i<=m;i++){
		int flag;
		scanf("%d",&flag);
		if(flag==1){
			cnt++;
			int l1,r1,l2,r2;
			scanf("%d%d%d%d",&l2,&r2,&l1,&r1);
			query[++tot]=(Query){1,l1-1,l2-1,1,cnt,1};
			query[++tot]=(Query){1,l1-1,r2,-1,cnt,1};
			query[++tot]=(Query){1,r1,l2-1,-1,cnt,1};
			query[++tot]=(Query){1,r1,r2,1,cnt,1};
		}
		else{
			int x,y;
			scanf("%d%d",&x,&y);
			query[++tot]=(Query){0,x,mp[x],0,0,-1}; 
			query[++tot]=(Query){0,y,mp[y],0,0,-1};
			swap(mp[x],mp[y]);
		 	query[++tot]=(Query){0,x,mp[x],0,0,1}; 
			query[++tot]=(Query){0,y,mp[y],0,0,1};
		} 
	}
	cdq(1,tot);
	for(int i=1;i<=cnt;i++)
		printf("%d\n",ans[i]);
}
//2 3
//1 2
//2 1
//1 1 1 1 1
//2 1 2
//1 1 1 1 1

  

---恢復內容結束---

Cideforces 1093E Intersection of Permutations (CDQ分治+樹狀數組)