百度首页 | 百度空间
 
查看文章
 
关于最长上升、下降子序列
2008-05-16 12:45
注意二分的写法,我的写的比较难看,=_=
http://202.120.80.191/problem.php?problemid=2106
最长下降
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int maxn =100001;
const int INFI =0x3fffffff;
struct Node{
       int x, y;
       bool operator < ( const Node &bj){
            if( x==bj.x) return y<bj.y;
            return x<bj.x;
       }
};
Node node[maxn];
int b[maxn];
int N, M, P;

void solve(){
     int i;
     for(i=1; i<=P; i++ )
              scanf("%d%d", &node[i].x, &node[i].y);
     sort( node+1, node+P+1);
     int x, res, ans, low, high, mid;
     ans=0;
     for( x=1; x<=P; x++ ){
          b[ans+1] =-INFI;
          low=1; high=ans+1;
                  if( ans==0 || node[x].y <b[ans] ){
                                b[++ans]=node[x].y; continue;
                  }
                  if( node[x].y>b[1]){
                          b[1]=node[x].y;       continue;
                  }
          while( low<high ){
                 mid =(low+high)/2;
                 if( b[mid] >node[x].y )
                     low =mid+1;
                 else
                     high =mid;
          }
          if( b[low]<node[x].y)
              res =low;
          else
              res =high;
          if( res>ans)
              ans++;
          b[res] =node[x].y;
     }
     printf("%d\n", ans);
}

int main(){
    freopen("D:\\in.txt", "r", stdin);   
    while( scanf("%d%d%d", &N, &M, &P)!=EOF ){
           solve();
    }
    return 0;
}

http://acm.zju.edu.cn/show_problem.php?pid=1986
最长上升
#include <stdio.h>
#include <string.h>

const int maxn =40001;
const int INFI =0x3fffffff;
int a[maxn], b[maxn];
int n;

void read(){
     scanf("%d", &n);
     for( int i=1; i<=n; i++)
          scanf("%d", a+i);    
}

void solve(){
     int x, low, high, mid, res, ans;
     ans=0;
     for( x=1; x<=n; x++){
          b[ans+1]=INFI;
                  if( ans==0 || a[x]>b[ans] ){
                          b[++ans] =a[x];
                          continue;
                  }
                  if( a[x]<b[1]){
                          b[1]=a[x];
                          continue;
                  }
          low=1; high=ans+1;
          while( low<high){
                 mid =(low+high)/2;
                 if( b[mid] >=a[x] )
                     high =mid;
                 else
                     low =mid+1;
          }
          if( b[low]<a[x] )
              res =high;
          else
              res =low;
          if( res>ans )
              ans++;
          b[res]=a[x];
     }
     printf("%d\n", ans);
}

int main(){
    freopen("D:\\in.txt", "r", stdin);   
    int testcase;
    scanf("%d", &testcase);
    while( testcase-- ){
           read();
           solve();
    }
    return 0;
}


类别:动态规划 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码:
 

     

©2008 Baidu