标签:dp
鏈接: http://acm.hdu.edu.cn/showproblem.php?pid=1160
Problem Description
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.
Output
Your program should output a sequence of lines of data; the first line should contain a number n; the remaining n lines should each contain a single positive integer (each one representing
a mouse). If these n integers are m[1], m[2],..., m[n] then it must be the case that
W[m[1]] < W[m[2]] < ... < W[m[n]]
and
S[m[1]] > S[m[2]] > ... > S[m[n]]
In order for the answer to be correct, n should be as large as possible.
All inequalities are strict: weights must be strictly increasing, and speeds must be strictly decreasing. There may be many correct outputs for a given input, your program only needs to find one.
Sample Input
6008 1300
6000 2100
500 2000
1000 4000
1100 3000
6000 2000
8000 1400
6000 1200
2000 1900
Sample Output
4
4
5
9
7
代碼如下:
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <algorithm> #define MAXN 10005 #define RST(N)memset(N, 0, sizeof(N)) using namespace std; typedef struct Node_ { int weight; int speed; int Num; }Node; Node N[MAXN]; int f[MAXN], p[MAXN]; int Max, position, i; int cmp(const void *a, const void *b) { Node *p1 = (Node *)a; Node *p2 = (Node *)b; if(p1->weight != p2->weight) return p1->weight - p2->weight; else return p2->speed - p1->speed; } void solve() { for(int j=1; j<i+1; j++) { for(int k=1; k<j; k++) { if(N[k].weight < N[j].weight && N[k].speed > N[j].speed) { if(f[k]+1 > f[j]) { f[j] = f[k] + 1; p[j] = k; if(f[j] > Max) { Max = f[j]; position = j; } } } } } printf("%d\n", Max); } void display(int position) { if(p[position] == position) { printf("%d\n", N[position].Num); return ; } display(p[position]); printf("%d\n", N[position].Num); } int main() { i = 1, Max = 0, position = 0; while(scanf("%d %d", &N[i].weight, &N[i].speed) != EOF) { f[i] = 1; p[i] = i; N[i++].Num = i; } qsort(N+1, i, sizeof(Node), cmp); solve(), display(position); return 0; }
HDU 1160 FatMouse's Speed (最長單調子序列 dp)
标签:dp
原文地址:http://blog.csdn.net/keshacookie/article/details/39051181