HDU1160-FatMouse's Speed【最长单调子序列】

FatMouse believes that the fatter a mouse is, the faster it runs. To disprove this, you want to take the data on a collection of mice and put as large a subset of this data as possible into a sequence so that the weights are increasing, but the speeds are decreasing. 

Input

Input contains data for a bunch of mice, one mouse per line, terminated by end of file. 

The data for a particular mouse will consist of a pair of integers: the first representing its size in grams and the second representing its speed in centimeters per second. Both integers are between 1 and 10000. The data in each test case will contain information for at most 1000 mice. 

Two mice may have the same weight, the same speed, or even the same weight and speed. 

思路:最长单调子序列问题,稍微变形一下就可以了。首先我们对数组进行排序,然后dp求解,用res数组记录下标,好回溯求解。

 

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1e3 + 10;
int dp[maxn], res[maxn];
struct mouse
{
    int idx;
    int w, v;
}a[maxn];
bool cmp(mouse x, mouse y)
{
    if(x.w == y.w)
        return x.v < y.v;
    return x.w > y.w;
}

int main()
{
    int i = 1;
    while(scanf("%d%d", &a[i].w, &a[i].v) != EOF)
    {
        a[i].idx = i;
        ++i;
    }
    int len = i - 1;
    memset(res, 0, sizeof(res));
    sort(a + 1, a + len + 1, cmp);
    for(int i = 0; i < maxn; ++i)
        dp[i] = 1;
    for(int i = 2; i <= len; ++i)
    {
        for(int j = 1; j < i; ++j)
        {
            if(a[i].w < a[j].w && a[i].v > a[j].v && dp[i] < dp[j] + 1)
            {
                dp[i] = dp[j] + 1;
                res[i] = j;
            }
        }
    }
    int pos = 0;
    for(int i = 1; i <= len; ++i)
    {
        if(dp[i] > dp[pos])
        {
            pos = i;
        }
    }
    printf("%d\n", dp[pos]);
    while(pos)
    {
        printf("%d\n", a[pos].idx);
        pos = res[pos];
    }
    return 0;
}

 

你可能感兴趣的:(动态规划,HDU)