題目大意:給出一個長度為 n 的數(shù)列 a ,構(gòu)造?s[ i ] 是數(shù)列 a 去掉 a[ i ] 后的數(shù)列,現(xiàn)在需要對 s 排序,輸出排序后的結(jié)果
題目分析:一提到排序,可以試著寫一下 sort 的 cmp ,然后剩下的就不用我們操心了
對于 cmp 函數(shù),我們的目標是給出兩個位置 x 和 y ,從而確定其相應(yīng)的大小
首先假設(shè) x < y ,這個時候,數(shù)列 s[ x ] 和 數(shù)列 s[ y ] 的長度肯定是相等的
如上圖所示,我們可以將整個數(shù)列分為三段,其中對于第一段和第三段而言,s[ x ] 和 s[ y ] 是完全相同的,只有在第二段中,這 y - x 個數(shù)是交叉對應(yīng)的,我們?yōu)榱吮容^兩個數(shù)列的大小,只需要找到位置 x 后的首個位置 pos?,滿足?a[ pos?] != a[ pos?+ 1 ] ,這個時候判斷一下這兩個數(shù)的大小就能比較出兩個數(shù)列的大小了,這里需要注意的點是,pos 需要滿足在區(qū)間 [ x , y ) 才行,如果 pos 不在這個區(qū)間內(nèi)的話,就說明 s[ x ] 和 s[ y ] 的第二段是相等的,綜上得出 s[ x ] 和 s[ y ] 是相等的
接下來考慮 x > y 的情況,其實就是上面把 x 和 y 的位置換一下,思路完全一樣
最后的問題就是,如何快速找到這個位置 pos 呢,我采取的一個方法就是,預(yù)處理把 a[ i ] != a[ i + 1 ] 的所有 i 都放到一個 vector 里,然后就可以二分查找了,這樣總的時間復(fù)雜度是 nlognlogn,對于 n = 1e5 的數(shù)據(jù)還是綽綽有余的
代碼: ?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<unordered_map>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;int a[N],ans[N];vector<int>pos;int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);int w;cin>>w;while(w--){pos.clear();int n;scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%d",a+i);ans[i]=i;}for(int i=1;i<n;i++)if(a[i]!=a[i+1])pos.push_back(i);//a[i]和a[i+1]不同pos.push_back(inf);sort(ans+1,ans+1+n,[&](int x,int y){if(x<y){int j=lower_bound(pos.begin(),pos.end(),x)-pos.begin();if(pos[j]<y)return a[pos[j]+1]<a[pos[j]]; }else{int j=lower_bound(pos.begin(),pos.end(),y)-pos.begin();if(pos[j]<x)return a[pos[j]+1]>a[pos[j]];}return x<y;});printf("%d",ans[1]);for(int i=2;i<=n;i++)printf(" %d",ans[i]);puts("");}return 0;
}