10131 - Is Bigger Smarter?

//题目信息http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1072
//本题主要是用动态规划。参考寂静山林的博客,写的非常详细(http://blog.csdn.net/metaphysis/article/details/6860405),这里只是做个个人随笔记录
//2012/2/28
//accepted
//
#include<iostream>
#include<algorithm>
#include<sstream>
using namespace std;

#define MAXNUM 1000

void backtrack(int index);

class elephant
{
public:
int index;
int weight;
int iq;
bool operator < (const elephant &other) const
{
if(weight!=other.weight)
return weight<other.weight;
else return iq>other.iq;
}
};

elephant elephants[MAXNUM];
int length[MAXNUM];
int parent[MAXNUM];
int main()
{
int index=0,weight,iq;
int i,j;
while(cin>>elephants[index].weight>>elephants[index].iq)
{
elephants[index].index=index;
index++;
}

sort(elephants,elephants+index);
for(i=0;i<index;++i)
{
length[i]=1;
parent[i]=-1;
}

int maxLength=0,maxIndex=0;
for(i=0;i<index;++i)
{
int iq=elephants[i].iq;
int weigth=elephants[i].weight;

for(j=0;j<i;++j)
{
if(elephants[j].weight<weigth && elephants[j].iq>iq)
if(length[i] <= length[j])
{
length[i]=length[j]+1;
parent[i]=j;
}
}

if(maxLength<length[i])
{
maxLength=length[i];
maxIndex=i;
}
}
cout<<maxLength<<endl;
backtrack(maxIndex);
return 0;
}

void backtrack(int index)
{
if(parent[index]!=-1)
backtrack(parent[index]);
cout<<elephants[index].index+1<<endl;
}

动态规划,回溯法输出解,以及父节点记录的方法。。

你可能感兴趣的:(BI)