标签:
求一个正整数序列的最长单调自增子序列,子序列不要求是连续的。例如
Input:5
5 2 4 3 1
Output:2
确定状态转移方程,设f[i]是以a[i]为结尾的最大值的子序列的长度,那么\[\max \{ f[i]\} \]的最大值就是要的结果。
所以转移方程为:
| \[f(i) = \max \{ f(x)|x < i,{a_i} > {a_x}\} + 1\] |
所以代码可以为:
void main(void)
{
int arr[] = {10,4,20,10,15,13};
int dist[6];
int path[6];
int num = 6;
int i = 0;
for(i = 0; i < 6; i++)
{
dist[i] = 0;
//-1表示前面没有元素了,用于回头求解的时候定界
path[i] = -1;
}
for(i = 0; i < num; i++)
{
int temp = 0;
int index = -1;
for(int j = i - 1; j >= 0; j--)
{
if(arr[i] > arr[j] && dist[j] > temp)
{
temp = dist[j];
index = j;
}//if
}//for
dist[i] = temp + 1;
path[i] = index;
}//for
//找到最大的那个值
int max = 0;
int maxIndex = -1;
for(int m = 0; m < num; m++)
{
if(dist[m] > max)
{
max = dist[m];
maxIndex = m;
}
}//for
printf("最长单曾子序列的长度是%d.\n", max);
while(path[maxIndex] != -1)
{
printf("%d->", arr[maxIndex]);
maxIndex = path[maxIndex];
}//while
printf("%d\n", arr[maxIndex]);
}
标签:
原文地址:http://www.cnblogs.com/stemon/p/4596883.html