若是兩個串\(i,j\)比較\(i < j\),若是離\(a_{i}\)最近的不一樣的數是\(a_{k}\),若是\(j < k\)那麼\(i\)排在\(j\)前面c++
不然的話若是\(a_{k} < a_{i}\),那麼\(i\)排在\(j\)前函數
因而寫個比較函數扔到sort裏就能夠了spa
#include <bits/stdc++.h> #define fi first #define se second #define pii pair<int,int> #define mp make_pair #define pb push_back #define space putchar(' ') #define enter putchar('\n') #define eps 1e-10 #define MAXN 1000005 #define ba 47 //#define ivorysi using namespace std; typedef long long int64; typedef unsigned int u32; typedef double db; template<class T> void read(T &res) { res = 0;T f = 1;char c = getchar(); while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); } while(c >= '0' && c <= '9') { res = res * 10 +c - '0'; c = getchar(); } res *= f; } template<class T> void out(T x) { if(x < 0) {x = -x;putchar('-');} if(x >= 10) { out(x / 10); } putchar('0' + x % 10); } int N,id[MAXN],nxt[MAXN]; char s[MAXN]; bool cmp(int a,int b) { bool f = 0; if(a > b) {f = 1;swap(a,b);} if(b < nxt[a]) f ^= 1; else { f ^= (s[nxt[a]] < s[a]); } return f; } void Solve() { read(N); scanf("%s",s + 1); for(int i = 1 ; i <= N ; ++i) { id[i] = i; } nxt[N] = N + 1; for(int i = N - 1 ; i >= 1 ; --i) { if(s[i + 1] != s[i]) nxt[i] = i + 1; else nxt[i] = nxt[i + 1]; } sort(id + 1,id + N + 1,cmp); for(int i = 1 ; i <= N ; ++i) { out(id[i]);space; } enter; } int main() { #ifdef ivorysi freopen("f1.in","r",stdin); #endif Solve(); }