最近写题目越来越少了,以至于这种简单题都会错……比赛的时候写了个n^2的算法,果断超时,赛后加了个剪枝,78ms
但是其实因为只要把有序序列中的连续不相等的两项交换,即可使之无序……所以o(n)就够了
o(n^2)
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #define INF 1E9 using namespace std; int a[100005],b[100005],c[100005]; bool cmp(int a,int b) { return a>b; } int main() { int n; scanf("%d",&n); if(n<=2){cout<<-1<<endl;return 0;} int j,i; for(i=0;i<n;i++) { scanf("%d",&a[i]); b[i]=c[i]=a[i]; } sort(b,b+n); if(b[0]==b[n-1]){cout<<-1<<endl;return 0;} sort(c,c+n,cmp); for(i=0;i<n;i++) { if(a[i]==a[i+1])continue; for(j=i+1;j<n;j++) { if(a[j]==a[j-1])continue; if(a[i]==a[j])continue; if((a[j]!=b[i]||a[i]!=b[j])&&(a[i]!=c[j]||a[j]!=c[i])) { cout<<i+1<<" "<<j+1<<endl; return 0; } } } cout<<-1<<endl; return 0; }
o(n)
#include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; int f[111111],n,i; main() { scanf("%d",&n); for(i=1; i<=n; i++)scanf("%d",&f[i]); for(i=2; i<=n; i++)if(f[i] != f[i-1]) { swap(f[i],f[i-1]); bool ok1 = true,ok2 = true; for(int j=2; j<=n; j++) { if(f[j-1]>f[j])ok1 = false; if(f[j-1]<f[j])ok2 = false; if(ok1 || ok2)continue; printf("%d %d",i-1,i); return 0; } swap(f[i],f[i-1]); } puts("-1"); return 0; }