Almost Sorted Array
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 2526 Accepted Submission(s): 627
Problem Description
We are all familiar with sorting algorithms: quick sort, merge sort, heap sort, insertion sort, selection sort, bubble sort, etc. But sometimes it is an overkill to use these algorithms for an almost sorted array.
We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array a1,a2,…,an , is it almost sorted?
We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array a1,a2,…,an , is it almost sorted?
Input
The first line contains an integer
T
indicating the total number of test cases. Each test case starts with an integer
n
in one line, then one line with
n
integers
a1,a2,…,an
.
1≤T≤2000
2≤n≤105
1≤ai≤105
There are at most 20 test cases with n>1000 .
1≤T≤2000
2≤n≤105
1≤ai≤105
There are at most 20 test cases with n>1000 .
Output
For each test case, please output "`YES`" if it is almost sorted. Otherwise, output "`NO`" (both without quotes).
Sample Input
3 3 2 1 7 3 3 2 1 5 3 1 4 1 5
Sample Output
YES YES NO
Source
Recommend
hujie
我们分析每一行种植玉米的状态其实之和前一行的种植状态有关系,和它前面的其余行没关系,这个满足无后效性, 题目让我们求的是方案总数,其实就是求最后一行的所有状态的方案数加和。 令dp[i][state]表示第i行状态为state的方案数,那么dp[i][state] += dp[i-1][pre_state],这里pre_state和state 必须满足条件,1:不相邻 2:pre_state和state是可以存在的,因为 有的地不能种植玉米,相应位不能为1,该转移方程可以理解为前一行的每一个pre_state都为第i行达到状态state贡 献了dp[i-1][pre_state]个方案数。#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int N=13; int dp[N][1<<N]; int n,m,a[N][N]; const int mod=100000000; int vst[1<<N],num; void getvalidstate() { num=0; for(int i=0;i<(1<<n);i++){ if((i&(i<<1)) == 0) vst[num++]=i; } } bool valid(int state,int row) { int flag=0; for(int i=0;i<n;i++) { if(!a[row][i+1]){ if(state&(1<<i)) { flag=1; } } } if(flag) return false; else return true; } int main() { while(~scanf("%d %d",&m,&n)) { memset(a,0,sizeof(a)); memset(dp,0,sizeof(dp)); for(int i=1;i<=m;i++) for(int j=1;j<=n;j++) scanf("%d",&a[i][j]); dp[0][0]=1; getvalidstate(); for(int i=1;i<=m;i++) /// 枚举每一行 { for(int j=0;j<num;j++) /// 枚举每一个满足条件的状态 { if(valid(vst[j],i)){ for(int k=0;k<num;k++){ if(valid(vst[k],i-1) && !(vst[j]&vst[k])){ dp[i][vst[j]]+=dp[i-1][vst[k]]; dp[i][vst[j]]%=mod; } } } } } int ans=0; for(int i=0;i<(1<<n);i++) { ans=(ans+dp[m][i])%mod; } printf("%d\n",ans); } return 0; }