HDU-5532-Almost Sorted Array【2015长春赛区】


Almost Sorted Array【2015长春赛区】–最长上升子序列


            Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

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?

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.

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

题目链接:HDU-5532

题目大意:给你一个序列,判断移除一个数字之和是否是单调递增或递减序列。

题目思路:现场赛的时候,这道题WA了11次,才AC。模拟写出来的,当时是判断是否存在逆序对,然后讨论删除哪个数字。很麻烦的做法。赛后才想到,可以用最长上升子序列来解这道题,不过需要nlogn的做法。/(ㄒoㄒ)/~~

以下是代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int arr[100010];
int ans[100010]; 
int arr2[100010];
//int Search(int num,int low,int high){  
//    int mid;  
//    while(low <= high)
//    {  
//        mid = (low + high) >> 1;  
//        if(num >= ans[mid]) low = mid + 1;  
//        else high = mid - 1;
//    }  
//    return low;  
//} 

int DP(int n)
{
    ans[1] = arr[1];
    int len = 1;
    for (int i = 2; i <= n; i++)
    {
        if (arr[i] >= ans[len])
        {
            len = len + 1;
            ans[len] = arr[i];
        }
        else
        {
        //  int pos = Search(arr[i],1,len);
            int pos = upper_bound(ans,ans + len,arr[i]) - ans; 
            ans[pos] = arr[i];
        }
    }
    return len;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--)
    {   
        int n;
        scanf("%d",&n);
        for (int i = 1; i <= n; i++)
        {
            scanf("%d",&arr[i]);
        }
        int len = DP(n);
        int flag = 0;
        if (len >= n - 1) flag = 1;
        else
        {
            //把数组反过来 
            for (int i = n,j = 1; j <= n; j++,i--)
            {
                arr2[j] = arr[i];
            }
            for (int i = 1, j = 1; i <= n; j++,i++)
            {
                arr[i] = arr2[i];
            }
            int len2 = DP(n);
            if (len2 >= n - 1) flag = 1;
        }
        if (flag) cout << "YES\n";
        else cout << "NO\n";
    }
    return 0;
}



你可能感兴趣的:(ACM_动态规划,HDU,Regionals,ACM解题报告)