ural 1078 Segments

来源:互联网 发布:冬天保湿面霜推荐 知乎 编辑:程序博客网 时间:2024/05/22 02:19
类型:DP

题目:http://acm.timus.ru/problem.aspx?space=1&num=1078

思路:按照长度从小到大进行排序,然后就是最长上升子序列,这样最优解一定可以得到

!!!模型的建立

// ural 1078. Segments// wa ac 0.031s#include <iostream>#include <string>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;#define FOR(i,a,b) for(i = (a); i < (b); ++i)#define FORE(i,a,b) for(i = (a); i <= (b); ++i)#define FORDE(i,a,b) for(i = (a); i >= (b); --i)const int MAXN = 510;const int INF = 0x7f7f7f7f;int n;int dp[MAXN], ed[MAXN];struct node {    int x, y, i;}p[MAXN];int cmp(node a, node b) {    return (a.y - a.x) < (b.y - b.x);}void solve() {    int i, j;    scanf("%d", &n);    FORE(i, 1, n) {        scanf("%d %d", &p[i].x, &p[i].y);        p[i].i = i;    }    sort(p + 1, p + n + 1, cmp);    FORE(i, 1, n)        dp[i] = 1;    FORE(i, 2, n) FORE(j, 1, i - 1)        if(p[i].x < p[j].x && p[i].y > p[j].y)            dp[i] = max(dp[i], dp[j] + 1);    int maxx = -INF, maxi = -1;    FORE(i, 1, n)        if(maxx < dp[i])            maxx = dp[i], maxi = i;    i = maxi - 1;    int t = maxi;    int cnt = 0;    ed[cnt++] = p[t].i;    while(i >= 1) {        while(!(dp[i] == dp[t] - 1 && (p[i].x > p[t].x && p[i].y < p[t].y))) {            --i;        }        if(i < 1)            break;        ed[cnt++] = p[i].i;        t = i--;    }    printf("%d\n", cnt);    FORDE(i, cnt - 1, 0)        (i == cnt - 1) ? printf("%d", ed[i]) : printf(" %d", ed[i]);    cout<<endl;}int main() {    solve();    return 0;}


原创粉丝点击