http://acm.nyist.net/JudgeOnline/problem.php?pid=214
先开设一个数组dp ,然后从第一个数开始枚举,和dp 数组中的最后一个元素end 进行比较,如果大于end 直接把这个数接到end 的后面,并且把end 更新为枚举的这个数。如果不大于edn ,在dp 数组中找到第一个大于这个数的位子 k,并用这个数 替换掉dp[k]。
例如:x = 5,dp【】 = {1,2,3,4}, 则枚举过x 之后,dp[] = {1,2,3,4,5 },
x = 5, dp[] = { 1,2,3,6,7}, 则枚举过x 之后,dp[] = { 1,2,3,5,7}
在查找x 在dp 数组中位子的时候可以用二分法, 也可以用STL中的lower_bound()。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int a[100010],dp[100010];
int inf = 0x7fffffff;
int binary_search(int x,int len)
{
int left = 1, right = len;
while(left <= right)
{
//cout<<left<<"***"<<right<<endl;
int mid = (left + right)/2;
if(x > dp[mid]) left = mid + 1;
else right = mid - 1;
}
return left;
}
int main()
{
int i,x,n,t,len;
while(cin>>n)
{
for(i = 0; i < n; i++)
cin>>a[i];
dp[1] = a[0];
len = 1;
for(i = 1; i < n; i++)
{
t = binary_search(a[i],len);
dp[t] = a[i];
if(t > len) len = t;
}
cout<<len<<endl;
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int Stack[100010];
int inf = 0x7fffffff;
int main()
{
int i,x,n;
while(cin>>n)
{
int top = 0;
Stack[top] = -inf;
for(i = 0; i < n; i++)
{
cin>>x;
if(x>Stack[top])
{
top++;
Stack[top] = x;
}
else
{
//int left = 1, right = top;
int left = lower_bound(Stack,Stack+top,x) - Stack;
// while(left <= right)
// {
// int mid = (left + right)/2;
// if(x > Stack[mid]) left = mid + 1;
// else right = mid -1;
// }
Stack[left] = x;
}
}
cout<<top<<endl;
}
return 0;
}
本文详细阐述了排序算法的应用场景及其实现过程,通过实例展示了如何使用数组和递增元素来优化排序效率,同时介绍了二分法搜索和STL库中的lower_bound()函数在查找操作中的高效应用。
513

被折叠的 条评论
为什么被折叠?



