10131 Is Bigger Smarter?(最长上升序列问题 + 记忆化搜索)
Some people think that the bigger an elephant is, the smarter it is. To disprove this, you want to take the data on a collection of elephants and put as large a subset of this data as possible into a sequence so that the weights are increasing, but the IQ's are decreasing.
The input will consist of data for a bunch of elephants, one elephant per line, terminated by the end-of-file. The data for a particular elephant will consist of a pair of integers: the first representing its size in kilograms and the second representing its IQ in hundredths of IQ points. Both integers are between 1 and 10000. The data will contain information for at most 1000 elephants. Two elephants may have the same weight, the same IQ, or even the same weight and IQ.
Say that the numbers on the i-th data line are W[i] and S[i]. 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 an elephant). If these n integers are a[1], a[2],..., a[n] then it must be the case that
W[a[1]] < W[a[2]] < ... < W[a[n]]and
S[a[1]] > S[a[2]] > ... > S[a[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 IQs must be strictly decreasing. There may be many correct outputs for a given input, your program only needs to find one.
6008 13006000 2100500 20001000 40001100 30006000 20008000 14006000 12002000 1900
44597
题意:输入一些大象的重量和IQ。要找出最长的序列满足重量从小到大,iq从大到小。
思路:记忆化搜索。搜过去,每次记录下序列长度,如果num + 1比序列长度小就不考虑。
代码:
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int dp[1005], i, j, Max, n, out[1005], way[1005];struct E {int w, iq, num;} e[1005];int cmp(E a, E b) {return a.w < b.w;}void dfs(int now, int num) {int i;for (i = 1; i < n; i ++) {if (e[now].iq > e[i].iq && e[i].w > e[now].w && dp[i] < num + 1) {dp[i] = num + 1;out[num] = i;dfs(i, num + 1);}}if (Max < num) {Max = num;for (i = 0; i < num; i ++)way[i] = out[i];}}int main() {n = 1;Max = 0;memset(way, 0, sizeof(way));memset(out, 0, sizeof(out));memset(dp, 0, sizeof(dp));memset(e, 0, sizeof(e));e[0].iq = 999999999;while (~scanf("%d%d", &e[n].w, &e[n].iq)) {e[n].num = n;n ++;}sort(e + 1, e + n, cmp);dfs(0, 0);printf("%d\n", Max);for (i = 0; i < Max; i ++)printf("%d\n", e[way[i]].num);return 0;}