您的位置:首页 > 其它

Is Bigger Smarter? - UVa 10131 dp

2014-07-26 11:50 357 查看

Question 1: Is Bigger Smarter?

The Problem

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
then it must be the case that
W[a[1]] < W[a[2]] < ... < W[a
]

and
S[a[1]] > S[a[2]] > ... > S[a
]

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.

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


题意:找一个最长的序列,使得w严格递增,s严格递减。

思路:先按w从小排,w相同的按s从小排,dp[]表示记录的更新的数值,pos[]表示当前的位置是哪个点,pre[]表示这个点的上一个节点是哪个。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{ int w,s,num;
}num[1010];
bool cmp(node a,node b)
{ if(a.w==b.w)
   return a.s<b.s;
  return a.w<b.w;
}
int dp[1010],pos[1010],pre[1010],len=1,ans[1010];
int solve(int k)
{ int l=1,r=len,mi;
  while(l<r)
  { mi=(l+r)/2;
    if(dp[mi]>k)
     l=mi+1;
    else
     r=mi;
  }
  return l;
}
int main()
{ int n=1,i,j,k;
  while(~scanf("%d%d",&num
.w,&num
.s))
  { num
.num=n;
    n++;
  }
  n--;
  sort(num+1,num+1+n,cmp);
  dp[1]=num[1].s;
  pos[1]=1;
  pre[1]=0;
  for(i=2;i<=n;i++)
  { if(num[i].s<dp[len])
    { dp[++len]=num[i].s;
      pos[len]=i;
      pre[i]=pos[len-1];
    }
    else
    { k=solve(num[i].s);
      dp[k]=num[i].s;
      pos[k]=i;
      pre[i]=pos[k-1];
    }
  }
  printf("%d\n",len);
  k=pos[len];
  for(i=len;i>=1;i--)
  { ans[i]=k;
    k=pre[k];
  }
  for(i=1;i<=len;i++)
   printf("%d\n",num[ans[i]].num);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: