1. 程式人生 > >HDU4638-Group (莫隊模板)

HDU4638-Group (莫隊模板)

There are n men ,every man has an ID(1..n).their ID is unique. Whose ID is i and i-1 are friends, Whose ID is i and i+1 are friends. These n men stand in line. Now we select an interval of men to make some group. K men in a group can create K*K value. The value of an interval is sum of these value of groups. The people of same group’s id must be continuous. Now we chose an interval of men and want to know there should be how many groups so the value of interval is max.
Input
First line is T indicate the case number.
For each case first line is n, m(1<=n ,m<=100000) indicate there are n men and m query.
Then a line have n number indicate the ID of men from left to right.
Next m line each line has two number L,R(1<=L<=R<=n),mean we want to know the answer of [L,R].
Output
For every query output a number indicate there should be how many group so that the sum of value is max.
Sample Input
1
5 2
3 1 2 5 4
1 5
2 4
Sample Output
1
2
題目:

HDU4638
題意:有n個人站成一隊,每個人都有一個獨一無二的序號x(1<= x <= n)。現給定n個人的順序及序號,每個區間裡,序號連續的人可以在一個組,現問給定區間中,能分成最小數量的組的個數。
思路:開始想用線段樹做,多次詢問區間的特性很適合線段樹,但是這題中合併兩個區間的複雜度太高了,實現困難,炸過記憶體,也T過。無果,於是學習了莫隊演算法。
莫隊演算法實現起來以及思路都很簡單,類似一個暴力,但神奇的是它的複雜度。雖然我至今認為它是n^2,但是它就是過了。
莫隊實現:
1.將詢問q[],按照x=q.l/(q.l^1/2)為第一關鍵字,q.r為第二關鍵字排序
2.用兩個指標currentl和currentr維護區間和答案,兩個詢問區間之間直接暴力跳轉

實現起來非常容易,我個人認為,當題目很像線段樹,但合併兩個區間的代價很大的情況下就應該嘗試莫隊,當然,帶修改也可以
AC程式碼:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#define met(s,k) memset(s,k,sizeof s)
#define scan(a) scanf("%d",&a)
#define scanl(a) scanf("%lld",&a) #define scann(a,b) scanf("%d%d",&a,&b) #define scannl(a,b) scanf("%lld%lld",&a,&b) #define scannn(a,b,c) scanf("%d%d%d",&a,&b,&c) #define prin(a) printf("%d\n",a) #define prinl(a) printf("%lld\n",a) using namespace std; typedef long long ll; const int maxn=1e5+10; int n,m,cont,ans,ans1[maxn]; struct que { int l,r,pos; }q[maxn]; bool cmp(que a,que b) { int x=a.l/cont; int y=b.l/cont; if(x!=y)return x<y; else return a.r<b.r; } int a[maxn],vis[maxn]; void removeposx(int pos)//暴力移動指標及維護答案 { if(vis[a[pos]-1]&&vis[a[pos]+1])ans+=1; else if(vis[a[pos]-1]==0&&vis[a[pos]+1]==0)ans-=1; vis[a[pos]]=0; } void addposx(int pos) { if(vis[a[pos]-1]&&vis[a[pos]+1])ans-=1; else if(vis[a[pos]-1]==0&&vis[a[pos]+1]==0)ans+=1; vis[a[pos]]=1; } void modui(int m) { int currenl=1,currenr=0; for (int i = 0; i <m; ++i)//注意自增和自減號的位置 { while (currenr<q[i].r)addposx(++currenr); while (currenr>q[i].r)removeposx(currenr--); while (currenl<q[i].l)removeposx(currenl++); while (currenl>q[i].l)addposx(--currenl); ans1[q[i].pos]=ans; } } int main() { int t; scan(t); while (t--) { scann(n,m); ans=0; met(vis,0); cont=(int)sqrt((double)n); for(int i=1;i<=n;i++)scan(a[i]); for(int i=0;i< m;i++)scann(q[i].l,q[i].r),q[i].pos=i; sort(q,q+m,cmp); modui(m); for (int j = 0; j <m; ++j)prin(ans1[j]); } return 0; }