最初没有多想,直接用最基本的DP写的代码,本想水过,可是测试数据超时。。。
DP O(n*n)算法代码:
#include<iostream>
using namespace std;
int main(){
const int SIZE = 1005;
int dp[SIZE];
int arr[SIZE];
int n;
while(cin>>n&&n!=0){
int max = 1;
for(int i=1;i<=n;i++){
cin>>arr[i];
dp[i]=1;
for(int j=i-1;j>=1;j--){//为dp[i]选取最大的dp[j]+1
if(dp[i]>=j+1)break;//剪枝
if(arr[i]>arr[j]&&dp[i]<dp[j]+1){
dp[i]=dp[j]+1;
}
}
if(dp[i]>max)
max=dp[i];
}
cout<<max<<endl;
}
return 0;
如果用贪心的话,可以将复杂度降到O(nlgn)
这个算法其实已经不是DP了,有点像贪心。至于复杂度降低其实是因为这个算法里面用到了二分搜索。本来有N个数要处理是O(n),每次计算要查找N次还是O(n),一共就是O(n^2);现在搜索换成了O(logn)的二分搜索,总的复杂度就变为O(nlogn)了。
这个算法的具体操作如下(by RyanWang):
开一个栈,每次取栈顶元素top和读到的元素temp做比较,如果temp > top 则将temp入栈;如果temp < top则二分查找栈中的比temp大的第1个数,并用temp替换它。 最长序列长度即为栈的大小top。
这也是很好理解的,对于x和y,如果x < y且Stack[y] < Stack[x],用Stack[x]替换Stack[y],此时的最长序列长度没有改变但序列Q的''潜力''增大了。
举例:原序列为1,5,8,3,6,7
栈为1,5,8,此时读到3,用3替换5,得到1,3,8; 再读6,用6替换8,得到1,3,6;再读7,得到最终栈为1,3,6,7。最长递增子序列为长度4。
用该算法完成POJ2533的具体代码如下:
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 |
#include <iostream> #define SIZE 1001 using namespace std; int main() { int i, j, n, top, temp; int stack[SIZE]; cin >> n; top = 0; /* 第一个元素可能为0 */ stack[0] = -1; for (i = 0; i < n; i++) { cin >> temp; /* 比栈顶元素大数就入栈 */ if (temp > stack[top]) { stack[++top] = temp; } else { int low = 1, high = top; int mid; /* 二分检索栈中比temp大的第一个数 */ while(low <= high) { mid = (low + high) / 2; if (temp > stack[mid]) { low = mid + 1; } else { high = mid - 1; } } /* 用temp替换 */ stack[low] = temp; } } /* 最长序列数就是栈的大小 */ cout << top << endl; //system("pause"); return 0; } |