UVA 497 Strategic Defense Initiative【最长严格递增子序列长度及打印】

题目大意:同标题。

解题策略:输入要注意,降序输出LIS可以用一个简单的递归搞定,升序花了点功夫。


/*
   UVA 497 Strategic Defense Initiative
   AC by J.Dark
   ON 2013/4/1
   Time 0.012s
*/ 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn = 10000;
int num[maxn], length[maxn], mark[maxn], numCount;

void Solve(){
     for(int i=1; i<=numCount; i++)   length[i] = 1;
     for(int i=1; i<=numCount; i++)   mark[i] = -1;
     //找出最大长度及序列
     for(int i=1; i<=numCount; i++){ 
        for(int j=1; j<i; j++){
           if(num[j] < num[i]){  //找出num[i]可跟在哪些数字之后 
              if(length[j]+1 > length[i]){
                 length[i] = length[j]+1;
                  mark[i] = j;  //num[i]接在num[j]之后 
              }
           }
        }
     }
     int maxAns = 0, maxPos;
     //找出上升序列最大长度  最大上升序列最末元素位置 
     for(int i=1; i<=numCount; i++){
        if(maxAns < length[i]){
           maxAns = length[i];
           maxPos = i;
        }
     } 
     int LIS[maxn], k = maxPos;
     for(int i=maxAns; i>0; i--){  //记录LIS 
        LIS[i] = num[k];
        k = mark[k];
     }
     printf("Max hits: %d\n", maxAns);
     for(int i=1; i<=maxAns; i++)   cout << LIS[i] << endl;

} 
///
int main(){
    int testCase;
    char temp[50];
    while(cin >> testCase)
    {
       getchar();   //万恶的输入,浪费时间……
       getchar();
       for(int i=0; i<testCase; i++){
          numCount = 0;
          while(gets(temp) && strlen(temp))
          {
             num[++numCount] = atoi(temp); //表示atoi函数让我感觉之前动不动字符流的方法土爆了…… 
          }
          if(i > 0) cout << endl; 
          Solve();
       }
    }
    
    //system("pause");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值