莫隊入門總結

這是一篇適合蒟蒻的講解**** 大佬可以自行離開****

莫隊是一種是離線的算法 , 即它在詢問的時候是不會修改的, 所以我們可以通過調整詢問的次序來獲得答案。

比如區間3到5和區間3到6 ,他們之間只差了1 , 於是我們只需要看下新加進來的這個元素對原來答案的影響就好了 , 對吧?

問題是: 我們應該如何給詢問區間排序使得時間複雜度最小呢???

這裏直接給出答案(主要是我太弱了 , 不會講 , 可以先自行思考 , 熟練了之後去看其他大佬的博客):
首先將整個區間分塊 , 將左端點按塊來排序 , 右端點按實際位置排序 ;
有點抽象 , 上代碼看看 :

struct question{
	int l , r , id ; 
	bool operator < (const question &a ) const { return pos[l] == pos[a.l] ? r < a.r : pos[l] < pos[a.l] ;}
}q[maxn];

其中pos存的是這個點所對應的塊的編號 ;

然後。。莫隊就結束了。。。

先上個例題看看:對着題講會好些
在這裏插入圖片描述
洛谷p2709

根據我們剛纔的思路 ,先把詢問排序 , 然後再移動區間即可 ;

手動模擬一下就可以懂了 ;
看圖 : 在這裏插入圖片描述
其中cnt是我目前各個數出現的次數 ;
簡簡單單 ;
上代碼:

#include<bits/stdc++.h>
using namespace std ;
#define maxn 50050
#define int long long
#define re register int
#define kkk signed main
#define mem(x) memset(x,0,sizeof(x))
inline int read(){
	int ans = 0 , f = 1 ; char ch = getchar() ;
	while(ch < '0'|| ch > '9' ) { if(ch == '-') f = -1 ; ch= getchar() ; }
	while(ch >= '0' && ch <= '9' ) ans = (ans << 3) + (ans << 1) + ch - '0' , ch = getchar() ;
	return ans ;
}
int  a[maxn] , pos[maxn] , L[maxn] , R[maxn] , cnt[maxn] , ans[maxn] , aans; 
int n , m , k , S , len ; 
struct question{
	int l , r , id ; 
	bool operator < (const question &a ) const { return pos[l] == pos[a.l] ? r < a.r : pos[l] < pos[a.l] ;}
}q[maxn];
inline void add(int x){
	aans-=cnt[a[x]]*cnt[a[x]];
    cnt[a[x]]++;
    aans+=cnt[a[x]]*cnt[a[x]];
}
inline void del(int x){
	aans-=cnt[a[x]]*cnt[a[x]];
    cnt[a[x]]--;
    aans+=cnt[a[x]]*cnt[a[x]];
}
kkk(){
//	freopen("1.in" , "r" , stdin) ; 
//	freopen("1.out" , "w" , stdout) ; 
	n = read() , m = read() ; k = read() ;
	for(int i  =1  ;i <= n / sqrt(n) + 1 ; i++)
	L[i] = 999999 ;
	S = sqrt(n) ; 
//	printf(" s : %lld\n" , S) ; 
	for(int i = 1 ; i <= n ; i++){
		a[i] = read() ; 
		pos[i] =  (i - 1)/ S + 1 ; 
		L[pos[i]] = min(L[pos[i]] , i) ; 
		R[pos[i]] = max(R[pos[i]] , i) ; 
	}
	for(int i = 1 ; i <= m ; i++){
		q[i].l = read() , q[i].r = read() ; 
		q[i].id = i  ; 
	}
	sort(q + 1 , q + 1 + m) ; 
	int l = 1 , r = 0 ; 
	for(int i = 1 ; i <= m ; i++){
		re ql = q[i].l , qr = q[i].r ; 
//		printf("query l : %lld r : %lld\n" , q[i].l , q[i].r ) ; 
		while(r < qr) add(++r) ; 
		while(r > qr) del(r--) ; 
		while(l < ql) del(l++) ; 
		while(l > ql) add(--l) ; 
		ans[q[i].id ] = aans ;  
	}
	for(int i = 1 ; i <= m ; i++){
		printf("%lld\n" , ans[i]) ; 
	}
	return 0 ;
}

其中L【i】 是第i塊的左端點 , pos是這點屬於第幾塊 , ans是存這個詢問的答案 ;

然後完結撒花✿✿ヽ(°▽°)ノ✿ ;

我太弱了可能沒講明白 自己多手摸幾次就好了)

莫隊最基礎就講完了 , 其實還有很多玄學優化 (要不然你會發現很多tle
你這可以在搞定這篇之後再去看其他人的(其實我不懂
再次強調:本篇博客只面向像我一樣的蒟蒻 , 如有不足 , 請各位神犇指出QWQ ;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章