Almost Sorted Array
题目链接:Almost Sorted Array
不用任何算法的做法:样例:1 3 6 5 7 8 9
9 8 7 5 6 3 2
2 7 1 1
AC代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <cmath> 6 using namespace std; 7 typedef long long ll; 8 # define INF 0x3f3f3f3f 9 10 int main() 11 { 12 ios::sync_with_stdio(false); 13 ll a[100010]; 14 ll t, n, f1, f2, pos1, pos2, p1, p2; 15 cin>>t; 16 while( t-- ) 17 { 18 cin>>n; 19 f1=0; 20 f2=0; 21 p1=0; 22 p2=0; 23 for(int i=1; i<=n; i++ ) 24 cin>>a[i]; 25 26 for(int i=2; i<=n; i++ ) 27 { 28 if( a[i]>a[i-1] ) 29 { 30 f1++; 31 pos1=i; 32 } 33 if( a[i]<a[i-1] ) 34 { 35 f2++; 36 pos2=i; 37 } 38 } 39 40 if( f1>1 && f2>1 ) 41 cout<<"NO"<<endl; 42 else if( f1==0 || f2==0 ) 43 cout<<"YES"<<endl; 44 else 45 { 46 if( f2==1 ) 47 { 48 a[0]=0; 49 a[n+1] = INF; 50 if( a[pos2-2]<=a[pos2] || a[pos2-1]<=a[pos2+1] ) 51 p2=1; 52 } 53 if( f1==1 ) 54 { 55 a[n+1]=0; 56 a[0]=INF; 57 if( a[pos1-1]>=a[pos1+1] || a[pos1]<=a[pos1-2] ) 58 p1=1; 59 } 60 if( p1||p2 ) 61 cout<<"YES"<<endl; 62 else 63 cout<<"NO"<<endl; 64 } 65 } 66 return 0; 67 }
用LDNS算法来实现:
题目分析:输出“YES“的情况为:1.原序列本来就是非递减或非递增序列,2.或原序列去掉一个元素就变成非递减或非递增序列
因为不能确定原序列是升序多还是降序多,所以对原序列求一次最长非递减子序列,倒序后在求一次
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <algorithm> 6 using namespace std; 7 8 typedef long long ll; 9 const ll maxn=100005; 10 11 int n; 12 int LDNS(int a[]) 13 { 14 int Cnt=0; 15 int Array[n+1]; 16 Array[0]=a[0]; 17 for(int i=1; i<n; i++ ) 18 { 19 if( a[i]>=Array[Cnt] ) 20 Array[++Cnt] = a[i]; 21 else 22 { 23 int Index = upper_bound(Array, Array+Cnt+1, a[i])-Array; 24 Array[Index] = a[i]; 25 } 26 } 27 return Cnt+1; 28 } 29 30 int main() 31 { 32 int T; 33 int a[maxn], b[maxn]; 34 cin>>T; 35 while( T-- ) 36 { 37 cin>>n; 38 for(int i=0; i<n; i++ ) 39 { 40 cin>>a[i]; 41 b[n-i-1]=a[i]; 42 } 43 int Len1=LDNS(a); 44 int Len2=LDNS(b); 45 if( Len1>=n-1 || Len2>=n-1 )//若是len1>=n-1,则是最长非递减序列,若是len2>=n-1,则是最长非上升序列 46 cout<<"YES"<<endl; 47 else 48 cout<<"NO"<<endl; 49 } 50 return 0; 51 }