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.
Example
input | output |
---|---|
4 -2 2 -1 1 -3 3 4 5 | 3 2 1 3 |
思路:
一道典型的DP问题,求得是最大包含的区间数,以及从内到外的包含关系(逐个输出)。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef long long ll;
const int maxN=505;
int N, dp[maxN], ans, pos;
struct node
{
int l,r,id;
}a[maxN];
bool cmp(node e1, node e2) { return e1.l==e2.l?(e1.r<e2.r):(e1.l>e2.l); }
int pre[maxN]; //前面那个数是什么?
void dfs(int k)
{
if(k==-1) return;
dfs(pre[k]);
printf("%d", k);
printf(k==pos?"\n":" ");
}
int main()
{
while(scanf("%d",&N)!=EOF)
{
fill(dp+1, dp+1+N, 1); ans=0;
memset(pre, -1, sizeof(pre));
for(int i=1; i<=N; i++)
{
scanf("%d%d",&a[i].l,&a[i].r);
a[i].id=i;
}
sort(a+1, a+1+N, cmp);
pos=2;
while(a[pos].l==a[pos-1].l)
{
dp[pos]=1;
pos++;
}
for(int i=pos; i<=N; i++)
{
for(int j=1; j<i; j++)
{
if(a[j].l>a[i].l && a[j].r<a[i].r)
{
if(dp[i]<dp[j]+1)
{
dp[i]=dp[j]+1;
pre[a[i].id]=a[j].id;
}
}
}
}
for(int i=1; i<=N; i++)
{
if(dp[i]>ans)
{
ans=dp[i];
pos=a[i].id;
}
}
printf("%d\n", ans);
dfs(pos);
}
return 0;
}