UVA - 10131 Is Bigger Smarter?(dp+最大升序子序列)

来源:互联网 发布:interbase数据库导出表 编辑:程序博客网 时间:2024/06/05 14:19
题目分析:
找出重量从小到大、智商从大到小排列的最长子序列。
并输出这些序列的编号。


解题思路:
1、对大象按IQ从大到小排序。
2、用最大升序子序列的方法,按照重量从小到大,求出最多的大象,用路径path[i]记下j(i之前那头大象)。

3、输出最长序列的长度,并递归输出路径。

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 1010;struct Node {int w,s,id;}e[N];int n;int dp[N],ans[N],path[N];bool cmp(Node a,Node b) {return a.s > b.s;}void print_path(int cur) {if(dp[cur] == 1) {printf("%d\n",e[cur].id);return;}print_path(path[cur]);printf("%d\n",e[cur].id);}int main() {n = 0;while(scanf("%d%d",&e[n].w,&e[n].s) != EOF) {e[n].id = n+1;n++;}sort(e,e+n,cmp);for(int i = 0; i < n; i++) {dp[i] = 1;path[i] = i;}int maxx = 0 , pos = 0;for(int i = 1; i < n; i++) {int maxd = 0;for(int j = 0; j < i; j++) {if(e[i].w > e[j].w && dp[j] > maxd) {maxd = dp[j];path[i] = j; //i之前的那个大象}}dp[i] = maxd + 1;if(maxx < dp[i]) {maxx = dp[i];pos = i;}}printf("%d\n",maxx);print_path(pos);return 0;}


0 0