poj 1887 Testing the CATCHER

#include<iostream>        //最长不上升子序列
using namespace std;

int main()
{
int cases=1,seq[10000],p;
while(scanf("%d",&p),p!=-1)
{
int rear=0;
seq[++rear]=p;
while(scanf("%d",&p),p!=-1)
{
if(p<=seq[rear]) //当p==seq[rear],可以压入最长不上升子序列中
seq[++rear]=p;

else
{
int s=1,t=rear,mid; //在最长不上升子序列中找到第一个严格小于p的数,并用p替换之(即使有相同元素出现).比如子序列是 4 3 , 要插入的值 p=4, 则子序列更新为 4 4
while(s<t)

{
mid=(s+t)/2;
if(seq[mid]>=p) //当seq[mid]==p时, s=mid+1, 因为p要替换的是比p小的数,而不是相等的数
s=mid+1;

else
t=mid;
}
seq[s]=p;
}
}
printf("Test #%d:\n maximum possible interceptions: %d\n\n",cases++,rear);
}
return 0;
}

 

 

最长不下降子序列
// 本题原是求最长不上升子序列,翻转过来就相当于求最长不下降子序列
#include<iostream> //最长不下降子序列
using namespace std;
int num[10000],seq[10000];
int main()
{
int cases=1,p;
while(scanf("%d",&p),p!=-1)
{
int len=0;
num[len++]=p;
while(scanf("%d",&p),p!=-1)
num[len++]=p;
for(int i=0;i<=(len-1)/2;++i)
swap(num[i],num[len-1-i]); //翻转原序列

seq[0]=num[0];
int rear=0;
for(int i=1;i<len;++i)
{
int p=num[i];
if(p>=seq[rear]) //当p==seq[rear],可以压入最长不下降子序列中
seq[++rear]=p;
else
{
int s=0,t=rear,mid; //在最长不下降子序列中找到第一个严格大于p的数,并用p替换之(即使有相同元素出现).比如子序列是 3 4 , 要插入的值 p=3, 则子序列更新为 3 3
while(s<t)
{
mid=(s+t)/2;
if(seq[mid]<=p) //当seq[mid]==p时, s=mid+1, 因为p要替换的是比p大的数,而不是相等的数
s=mid+1;
else
t=mid;
}
seq[s]=p;
}
}
printf("Test #%d:\n maximum possible interceptions: %d\n\n",cases++,rear+1);
}
return 0;
}



posted on 2011-07-22 20:10  sysu_mjc  阅读(109)  评论(0编辑  收藏  举报

导航