UVA11456 Trainsorting【LIS+DP】

拜拜、爱过 提交于 2020-04-06 18:03:58

Erin is an engineer. She drives trains. She also arranges the cars within each train. She prefers to put the cars in decreasing order of weight, with the heaviest car at the front of the train.
    Unfortunately, sorting train cars is not easy. One cannot simply pick up a car and place it somewhere else. It is impractical to insert a car within an existing train. A car may only be added to the beginning and end of the train.
    Cars arrive at the train station in a predetermined order. When each car arrives, Erin can add it to the beginning or end of her train, or refuse to add it at all. The resulting train should be as long as possible, but the cars within it must be ordered by weight.
    Given the weights of the cars in the order in which they arrive, what is the longest train that Erin can make?
Input
The first line is the number of test cases to follow. The test cases follow, one after another; the format of each test case is the following:
    The first line contains an integer 0 ≤ n ≤ 2000, the number of cars. Each of the following n lines contains a non-negative integer giving the weight of a car. No two cars have the same weight.
Output
Output a single integer giving the number of cars in the longest train that can be made with the given restrictions.
Sample Input
1
3
1
2
3
Sample Output
3















问题链接UVA11456 Trainsorting
问题简述:给定n表示有n节车厢,然后给定每节车厢(i)的重量,第i节位于第i个车站,列车长有强迫症,要求列车的车箱要按照质量从大到小排序,所以他按照序号一次经过每一个车站,并且可以考虑是否添加位于该车站的车厢,添加的话也只能放在已有车列的前端和后端,不能从中间插入,计算列车最多能有多长?
问题分析:进行双向的LIS,然后取最大值。
程序说明:(略)
参考链接:(略)
题记:(略)




AC的C++语言程序如下:

/* UVA11456 Trainsorting */

#include <bits/stdc++.h>

using namespace std;

const int N = 2000;
int a[N], dp1[N], dp2[N];

int main()
{
    int t, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);

        memset(dp1, 0, sizeof(dp1));
        memset(dp2, 0, sizeof(dp2));
        int maxlen = 0;
        for(int i = n - 1; i >= 0; i--) {
            dp1[i] = dp2[i] = 1;
            for(int j = n - 1; j > i; j--) {
                if(a[i] > a[j]) dp1[i] = max(dp1[i], dp1[j] + 1);
                if(a[i] < a[j]) dp2[i] = max(dp2[i], dp2[j] + 1);
            }
            maxlen = max(maxlen, dp1[i] + dp2[i] - 1);
        }
        printf("%d\n", maxlen);
    }

    return 0;
}
发布了2247 篇原创文章 · 获赞 2366 · 访问量 262万+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!