1078. Segments
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
A number of segments are lying on a line. Every segment is given with the coordinates of its endpoints. Segments are numbered from 1 to
N (0 <
N < 500). We assume, that one segment is inside another, if the two segments are different, the first one is fully contained in the second one, and their endpoints do not coincide. Write a program, which finds the numbers of the segments in the longest sequence of segments which are contained in. In the sequence, every segment except the last is inside the next segment in the sequence.
Input
The first line contains one integer
N. Next, there are
N lines, with two integers on every line, which are the coordinates of the left and the right endpoints of the corresponding segment. These coordinates are integers in the interval [–10000, 10000]. We assume that, the given segments are numbered according to their place in the input.
Output
The first line must contain one integer, equal to the number of segments in the found sequence. The following line must contain the numbers of the segments in this sequence. These numbers must be outputted, in the order in which the segments' lengths increase, starting from the smallest. If there are more than one output sequences, write any of them.
Sample
input | output |
---|---|
4 -2 2 -1 1 -3 3 4 5 | 3 2 1 3 |
给出一个数列S中的N个元素,数列中的每个元素有两个参数,分别为A,B,从数列中取出M个元素,使得对于任意两个取出的元素Si,Sj(1<=i<j<=m),均有Ai<Aj&&Bi>Bj或者Ai>Aj,Bi<Bj(就是包含关系)求M的最大值,以及这M个数,按顺序输他们在原数列中的位置
题解:
这题so easy,先按x降序排次序,然后找y的最大递增子序列就可以了,不过最后回溯输出要稍微注意下
代码:
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct Line{
int x,y,no;
}a[501];
int f[501],p[501],ans[501];
bool cmp(Line a,Line b)
{
return ((a.x>b.x)||(a.x==b.x&&a.y>b.y));
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
a[i].no=i+1;
}
sort(a,a+n,cmp);
f[0]=1;
int m=1,t=0;
for(int i=1;i<n;i++)
{
f[i]=1;
for(int j=0;j<=i-1;j++)
{
if(a[i].y>a[j].y&&f[j]+1>f[i])
{
f[i]=f[j]+1;
p[i]=j;
}
if(f[i]>m)
{
m=f[i];
t=i;
}
}
}
printf("%d\n",m);
int cnt=0;
while(m--)
{
ans[cnt++]=a[t].no;
t=p[t];
}
for(int i=cnt-1;i>0;i--)
printf("%d ",ans[i]);
printf("%d\n",ans[0]);
return 0;
}