UVa 10131: Is Bigger Smarter?

动态规划题。类似UVa103 Stacking Box,都是题目给一种判断嵌套的方法然后求最长序列。提前对数据排序可以节省一些时间开销。

我的解题代码如下:

 

#include <iostream>

#include <cstdio>

#include <cstring>

#include <cstdlib>

#include <algorithm>



using namespace std;



#define MAXN 1005

int N;

int w[MAXN],s[MAXN];

int Rank[MAXN],Index[MAXN],NextInSeq[MAXN],LongLen[MAXN];

int cmp(const void *a, const void *b)

{

	int ai = *(int *)a, bi = *(int *)b;

	if(w[ai]!=w[bi]) return w[ai]-w[bi];

	return s[bi]-s[ai];

};

int dp(int n)

{

	if(LongLen[n]) return LongLen[n];

	int k = Index[n];

	for(int i=k+1; i<N; i++) if(w[n]<w[Rank[i]] && s[n]>s[Rank[i]]) if(LongLen[n]<dp(Rank[i]))

	{

		LongLen[n] = dp(Rank[i]);

		NextInSeq[n] = Rank[i];

	}

	return ++LongLen[n];

}

int main()

{

	N=0;

	while(scanf("%d %d",&w[N],&s[N])==2) N++;

	for(int i=0; i<N; i++) Rank[i] = i;

	qsort(Rank,N,sizeof(int),cmp);

	for(int i=0; i<N; i++) Index[Rank[i]] = i;

	memset(LongLen,0,sizeof(LongLen));



	int anslen = 0, ansi;

	for(int i=0; i<N; i++) if(anslen<dp(i)) { anslen = dp(i); ansi = i; }

	printf("%d\n%d\n",anslen,ansi+1);

	for(int i=1; i<anslen; i++) { ansi = NextInSeq[ansi]; printf("%d\n",ansi+1); }

	return 0;

}


 

 

你可能感兴趣的:(uva)