莫隊算法——解決序列上詢問的利器

問題:
有一個長爲N序列,有M個詢問:在區間[L,R]內,出現了多少個不同的數字。(序列中所有數字均小於K)。題目會給出K。

莫隊算法就是滋磁解決這類問題的離線算法。(其實很簡單

首先來看看暴力:
由於暴力還是比較水的,所以直接上:

#include <bits/stdc++.h>
using namespace std ;
const int maxn = 50010 ;
int n, m, a[maxn] ;
bool vis[maxn] ;
int main() {
    int i, j, k, query_time, L, R ;
    cin >> n >> query_time >> k ;
    for ( i = 1 ; i <= n ; i ++ ) 
        cin >> a[i] ;
    while ( query_time -- ) {
        cin >> L >> R ;
        memset ( vis, 0, sizeof(vis) ) ;
        for ( i = L ; i <= R ; i ++ ) 
            vis[a[i]] = true ;
        int ans = 0 ;
        for ( i = 0 ; i <= k ; i ++ ) 
            ans += vis[i] ;
        cout << ans << endl ;
    }
    return 0 ;
}

這個複雜度顯然是 O(N2) 的。有些題目的範圍可能到100000或者更大,那麼顯然就不能了。

這裏還有一種稍作改進的方法,比上述做法大多數情況要快些。

void add ( int pos ) {
    ++cnt[a[pos]] ;
    if ( cnt[a[pos]] == 1 ) 
        ++ answer ;
}
void remove ( int pos ) {
    -- cnt[a[pos]] ;
    if ( cnt[a[pos]] == 0 ) 
        -- answer ;
}
void solve() {
    int curL = 1, curR = 0 ; // current L R 
    for ( each query [L,R] ) {
        while ( curL < L ) 
            remove ( curL++ ) ;
        while ( curL > L ) 
            add ( --curL ) ;
        while ( curR < R ) 
            add ( ++curR ) ;
        while ( curR > R ) 
            remove ( curR-- ) ;
        cout << answer << endl ;
        // Warning : please notice the order "--","++" and "cur" ;
    }
}

其實還算好理解的,如果不明白,隨便搞組數據手玩一下就明白了

手玩數據:
6 4 3
1 3 2 1 1 3
1 4
2 6
3 5
5 6
輸出答案:
3
2
2

不幸的是,雖然這個東西比我們的暴力要快,但是它的時間複雜度仍然是 O(N2) 的。
但好消息是,這個東西可以算是莫隊算法的核心了。(你在逗我笑????)
其實是真的 :)

莫隊算法是怎麼做的呢?
考慮到上述改進的辦法的效率低下主要是因爲curL和curR兩個指針前前後後跑來跑去太多次。於是,我們的做法就是不要讓他們跑太多沒用的距離。
我們可以通過離線下所有的詢問,然後通過某種排序,讓兩個指針跑動的距離儘量變少。具體的做法是把N劃分成N 段,每段長度都是N ,然後在把所有詢問按照L端點排序,看各個詢問被劃分到哪一塊裏。接着,對於各個劃分出的段,在各自的段裏,將它包含的所有區間再按照R端點排序。
舉個例子:假設我們有3個長度爲3的段(0-2,3-5,6-8):
{0, 3} {1, 7} {2, 8} {7, 8} {4, 8} {4, 4} {1, 2}
先根據所在段落的編號重排
{0, 3} {1, 7} {2, 8} {1, 2} | {4, 8} {4, 4} | {7, 8}
現在按R的值重排
{1, 2} {0, 3} {1, 7} {2, 8} | {4, 4} {4, 8} | {7, 8}

然後?還要然後嗎?就用剛剛那個算法來玩就好了。畢竟我們只是交換了一下詢問的順序而已,並沒有對算法做什麼改動。

對於這個的複雜度嘛,其實是比較鬼畜的,就這麼改了下順序,然後就變成了O(NN)

上面代碼所有查詢的複雜性是由4個while循環決定的。前2個while循環是curL的移動總量”,後2個while循環是curR的移動總量”。這兩者的和將是總複雜度。
有趣的是。先考慮右指針:對於每個塊,查詢是遞增的順序排序,所以右指針curR按照遞增的順序移動。在下一個塊的開始時,指針是儘量靠右的 ,將移動到下一個塊中的最小的R處。這意味着對於一個給定的塊,右指針移動的量是 O(N) 。我們有O(N) 個塊。所以總共是O(NN)
關於左指針:所有查詢的左指針都在同一段中,當我們完成一個查詢到下一個查詢時,左指針會移動,但由於兩次詢問的L在同一塊中,此移動是
O(N) 的。所以,左指針的移動總量是O(MN)
所以,總複雜度就是O((N+M)N) ,就當做是O(NN) 吧。
是不是很簡單的吶2333

接下來給幾個例題:

例題1:BZOJ3781 小B的詢問

Description

小B有一個序列,包含N個1~K之間的整數。他一共有M個詢問,每個詢問給定一個區間[L..R],求Sigma(c(i)^2)的值,其中i的值從1到K,其中c(i)表示數字i在[L..R]中的重複次數。小B請你幫助他回答詢問。

Input

第一行,三個整數N、M、K。
第二行,N個整數,表示小B的序列。
接下來的M行,每行兩個整數L、R。

Output

M行,每行一個整數,其中第i行的整數表示第i個詢問的答案。

Sample Input

6 4 3
1 3 2 1 1 3
1 4
2 6
3 5
5 6

Sample Output

6
9
5
2

HINT

對於全部的數據,1<=N、M、K<=50000

很裸的吧~

/**************************************************************
    Source Code : GoAway
    Date : 2017-02-06
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <ctime>

using namespace std ;
const int zhf = 1<<30 ;
const int maxn = 50010, tim = 250 ;
bool Read ( int &x ) {
    bool f = 0 ; x = 0 ; char c = getchar() ; 
    while ( !isdigit(c) ) {
        if ( c == '-' ) f = 1 ;
        if ( c == EOF ) return false ;
        c = getchar() ;
    }
    while ( isdigit(c) ) {
        x = 10 * x + c - '0' ;
        c = getchar() ;
    }
    if ( f ) x = -x ;
    return true ;
}

struct query {
    int L, R, id ;
    friend bool operator < ( query a, query b ) {
        return (a.L/tim) == (b.L/tim) ? a.R < b.R : a.L < b.L ;
    }
} e[maxn] ;

int n, m, a[maxn], cnt[maxn], ans[maxn], answer ;
void add ( int pos ) {
    answer += (cnt[a[pos]]++)<<1|1 ;
}
void remove ( int pos ) {
    answer -= (--cnt[a[pos]])<<1|1 ;
}

int main() {
    int i, j, k, curL = 1, curR = 0 ;
    Read(n) ; Read(m) ; Read(j) ;
    for ( i = 1 ; i <= n ; i ++ ) 
        Read(a[i]) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        Read(e[i].L) ;
        Read(e[i].R) ;
        e[i].id = i ;
    }
    sort ( e+1, e+m+1 ) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        int L = e[i].L, R = e[i].R ;
        while ( curL < L ) 
            remove ( curL++ ) ;
        while ( curL > L ) 
            add ( --curL ) ;
        while ( curR < R ) 
            add ( ++curR ) ;
        while ( curR > R ) 
            remove ( curR-- ) ;
        ans[e[i].id] = answer ;
    }
    for ( i = 1 ; i <= m ; i ++ ) 
        printf ( "%d\n", ans[i] ) ;
    return 0 ;
}

例題2:SDOI2009 HH的項鍊 洛谷1972

Description

HH有一串由各種漂亮的貝殼組成的項鍊。HH相信不同的貝殼會帶來好運,所以每次散步 完後,他都會隨意取出一段貝殼,思考它們所表達的含義。HH不斷地收集新的貝殼,因此, 他的項鍊變得越來越長。有一天,他突然提出了一個問題:某一段貝殼中,包含了多少種不同 的貝殼?這個問題很難回答。。。因爲項鍊實在是太長了。於是,他只好求助睿智的你,來解 決這個問題。

Input

第一行:一個整數N,表示項鍊的長度。 第二行:N個整數,表示依次表示項鍊中貝殼的編號(編號爲0到1000000之間的整數)。 第三行:一個整數M,表示HH詢問的個數。 接下來M行:每行兩個整數,L和R(1 ≤ L ≤ R ≤ N),表示詢問的區間。

Output

M行,每行一個整數,依次表示詢問對應的答案。

Sample Input

6
1 2 3 4 3 5
3
1 2
3 5
2 6

Sample Output

2
2
4

HINT

對於20%的數據,N ≤ 100,M ≤ 1000;
對於40%的數據,N ≤ 3000,M ≤ 200000;
對於100%的數據,N ≤ 50000,M ≤ 200000。

還是很裸的2333

/**************************************************************
    Source Code : GoAway
    Date : 2017-02-06
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <ctime>

using namespace std ;
const int zhf = 1<<30 ;
const int maxn = 1000010 ;
bool Read ( int &x ) {
    bool f = 0 ; x = 0 ; char c = getchar() ;
    while ( !isdigit(c) ) {
        if ( c == '-' ) f = 1 ;
        if ( c == EOF ) return false ;
        c = getchar() ;
    }
    while ( isdigit(c) ) {
        x = 10 * x + c - '0' ;
        c = getchar() ;
    }
    if ( f ) x = -x ;
    return true ;
}

int n, m, cnt[maxn], a[maxn], answer, ans[maxn], tim ;
struct query {
    int l, r, id ;
    friend bool operator < ( query a, query b ) {
        return (a.l/tim) == (b.l/tim) ? a.r < b.r : a.l<b.l ;
    }
} e[maxn] ;
void add ( int pos ) {
    if ( (++cnt[a[pos]]) == 1 ) ++ answer ;
}
void remove ( int pos ) {
    if ( (--cnt[a[pos]]) == 0 ) -- answer ;
}
int main() {
    int i, j, k, curL = 1, curR = 0 ;
    Read(n) ;
    for ( i = 1 ; i <= n ; i ++ ) 
        Read(a[i]) ;
    Read(m) ; tim = sqrt(m) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        Read(e[i].l) ;
        Read(e[i].r) ;
        e[i].id = i ;
    }
    sort(e+1,e+m+1) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        int L = e[i].l, R = e[i].r ;
        while ( curL < L ) 
            remove(curL++) ;
        while ( curL > L ) 
            add(--curL) ;
        while ( curR < R ) 
            add(++curR) ;
        while ( curR > R ) 
            remove(curR--) ;
        ans[e[i].id] = answer ;
    }
    for ( i = 1 ; i <= m ; i ++ ) 
        printf ( "%d\n", ans[i] ) ;
    return 0 ;
}

例題3:2009國家集訓隊 小Z的襪子 清橙OJ1206

問題描述
  作爲一個生活散漫的人,小Z每天早上都要耗費很久從一堆五顏六色的襪子中找出一雙來穿。終於有一天,小Z再也無法忍受這惱人的找襪子過程,於是他決定聽天由命……
  具體來說,小Z把這N只襪子從1到N編號,然後從編號L到R(L 儘管小Z並不在意兩隻襪子是不是完整的一雙,甚至不在意兩隻襪子是否一左一右,他卻很在意襪子的顏色,畢竟穿兩隻不同色的襪子會很尷尬。
  你的任務便是告訴小Z,他有多大的概率抽到兩隻顏色相同的襪子。當然,小Z希望這個概率儘量高,所以他可能會詢問多個(L,R)以方便自己選擇。
輸入格式
  輸入文件第一行包含兩個正整數N和M。N爲襪子的數量,M爲小Z所提的詢問的數量。
  接下來一行包含N個正整數Ci,其中Ci表示第i只襪子的顏色,相同的顏色用相同的數字表示。
  再接下來M行,每行兩個正整數L,R表示一個詢問。
輸出格式
  輸出文件包含M行,對於每個詢問在一行中輸出分數A/B表示從該詢問的區間[L,R]中隨機抽出兩隻襪子顏色相同的概率。若該概率爲0則輸出0/1,否則輸出的A/B必須爲最簡分數。(詳見樣例)
樣例輸入
6 4
1 2 3 3 3 2
2 6
1 3
3 5
1 6
樣例輸出
2/5
0/1
1/1
4/15
樣例說明
  詢問1:共C(5,2)=10種可能,其中抽出兩個2有1種可能,抽出兩個3有3種可能,概率爲(1+3)/10=4/10=2/5。
  詢問2:共C(3,2)=3種可能,無法抽到顏色相同的襪子,概率爲0/3=0/1。
  詢問3:共C(3,2)=3種可能,均爲抽出兩個3,概率爲3/3=1/1。
  注:上述C(a, b)表示組合數,組合數C(a, b)等價於在a個不同的物品中選取b個的選取方案數。
數據規模和約定
  30%的數據中 N,M ≤ 5000;
  60%的數據中 N,M ≤ 25000;
  100%的數據中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。

這道題倒是有些需要想想。
但是有一個神奇的事情:C(N,M)=N!M!(NM)!
那麼C(N,2)呢?
這不就是一個N1i=1i 嘛?
(有沒有感覺自己被續了一秒

/**************************************************************
    Source Code : GoAway
    Date : 2017-02-06
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <ctime>
#define ll long long
using namespace std ;
const ll zhf = 1<<30 ;
const ll maxn = 50010 ;
bool Read ( ll &x ) {
    bool f = 0 ; x = 0 ; char c = getchar() ;
    while ( !isdigit(c) ) {
        if ( c == '-' ) f = 1 ;
        if ( c == EOF ) return false ;
        c = getchar() ;
    }
    while ( isdigit(c) ) {
        x = 10 * x + c - '0' ;
        c = getchar() ;
    }
    if ( f ) x = -x ;
    return true ;
}
ll tim ;
struct query {
    ll L, R, id ;
    friend bool operator < ( query a, query b ) {
        return (a.L/tim) == (b.L/tim) ? a.R < b.R : a.L < b.L ;
    }
} e[maxn] ;
ll gcd ( ll x, ll y ) {
    return y ? gcd ( y, x%y ) : x ;
}
struct Answer {
    ll x, y ;
    void out() {
        if ( !x ) puts("0/1") ;
        else {
            ll d = gcd(x, y) ;
            x /= d ; y /= d ;
            printf ( "%lld/%lld\n", x, y ) ;
        }
    }
} ans[maxn] ;

ll n, m, a[maxn], cnt[maxn], answer ;
void add ( ll pos ) {
    ++ cnt[a[pos]] ;
    if ( cnt[a[pos]] > 1 ) 
        answer += cnt[a[pos]] - 1 ;
}
void remove ( ll pos ) {
    -- cnt[a[pos]] ;
    if ( cnt[a[pos]] > 0 ) answer -= cnt[a[pos]] ;
}
ll sum ( ll x ) { return x*(x+1)/2 ; }
int main() {
    ll i, j, k, curL = 1, curR = 0 ;
    Read(n) ; Read(m) ;
    tim = sqrt(m) ;
    for ( i = 1 ; i <= n ; i ++ ) 
        Read(a[i]) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        Read(e[i].L) ; Read(e[i].R) ;
        e[i].id = i ;
    }
    sort ( e+1, e+m+1 ) ;
    for ( i = 1 ; i <= m ; i ++ ) {
        ll L = e[i].L, R = e[i].R ;
        while ( curL < L ) 
            remove ( curL++ ) ;
        while ( curL > L ) 
            add ( --curL ) ;
        while ( curR < R ) 
            add ( ++curR ) ;
        while ( curR > R ) 
            remove ( curR-- ) ;
        ans[e[i].id] = (Answer){answer,sum(R-L)} ;
    }
    for ( i = 1 ; i <= m ; i ++ ) 
        ans[i].out() ;
    return 0 ;
}

其實莫隊還可以套上樹狀數組或者在一棵樹上搞的,但是這篇文章就簡單先介紹下啦~
要是俺有空就出莫隊的續集,嘿嘿~

可修改的莫隊戳這裏

發佈了55 篇原創文章 · 獲贊 39 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章