做这道题的时候想到了 CSP-2022 S T3 ,于是用与之类似的 hash 做了过去。
题目做法
显然,反转后的序列一定有序,怎么用 hash 体现有序性呢?
考虑对每一个位置随机附一个权值,记作 $val_i$,则 $\sum_{i=1}^{n} i\times val_i$ 是排列有序的条件,正确性显然。
那么现在排列的权值为 $\sum_{i=1}^{n} a_i\times val_i$ ,暴力交换查看是否与目标权值相同即可。
时间复杂度为 $\Theta(n^3)$ ,但是枚举左右端点和交换时都有一半的常数,程序本身常数较小,故可以较为轻松的跑过
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <bits/stdc++.h> using namespace std; const int N=1e5+10; #define OK cerr<<"OK"<<endl; #define int long long const int mod=998244353; template <typename T> inline void read(T& x){ x=0;T f=1;char ch=getchar();while(ch<'0'||ch>'9') {if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();x=x*f;return; } template <typename T,typename ...Arg>void read(T& x,Arg& ...arg){read(x);read(arg...);} template <typename T>void write(T x){ if(x<0)putchar('-'),x=-x;if(x<10)putchar(x+'0'); else write(x/10),putchar(x%10+'0'); } template <typename T,typename ...Arg>void write(T& x,Arg& ...arg){write(x);putchar(' ');write(arg...);} void writek(int x){write(x);putchar(' ');} void writeh(int x){write(x);putchar('\n');}
mt19937 e(time(NULL)); uniform_int_distribution<int>d(1,1e5); int val[N],a[N],sum,tmpp,n; signed main(){ read(n); for(int i=1;i<=n;i++){ read(a[i]); val[i]=d(e); tmpp+=val[i]*a[i]; sum+=val[i]*i; } for(int l=1;l<=n;l++){ for(int r=l+1;r<=n;r++){ int tmp=tmpp; for(int k=l;k<=(l+r)/2;k++){ tmp+=a[r-k+l]*val[k]-a[k]*val[k]; tmp+=a[k]*val[r-k+l]-a[r-k+l]*val[r-k+l]; } if(tmp==sum){ write(l,r); return 0; } } } puts("0 0"); return 0; }
|