1245: Trainsorting
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 14 Solved: 12
[ Submit][ Status][ Web Board]
Description
Erin is an engineer. She drives trains. She also arranges the cars within each train. She prefers to put the cars in decreasing order of weight, with the heaviest car at the front of the train.
Unfortunately, sorting train cars is not easy. One cannot simply pick up a car and place it somewhere else. It is impractical to insert a car within an existing train. A car may only be added to the beginning and end of the train.
Cars arrive at the train station in a predetermined order. When each car arrives, Erin can add it to the beginning or end of her train, or refuse to add it at all. The resulting train should be as long as possible, but the cars within it must be ordered by weight.
Given the weights of the cars in the order in which they arrive, what is the longest train that Erin can make?
Input
The first line contains an integer 0 <= n <= 2000, the number of cars. Each of the following n lines contains a non-negative integer giving the weight of a car. No two cars have the same weight.
Output
Output a single integer giving the number of cars in the longest train that can be made with the given restrictions.
Sample Input
Sample Output
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n,i,j,sum;
int b[2001];
int c[2001];
int a[2001];
while(~scanf("%d",&n))
{
sum=0;
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=n;i>=1;i--)
{
b[i]=1;
c[i]=1;
for(j=n;j>i;j--)
{
if(a[i]>a[j])
{
b[i]=max(b[i],b[j]+1);
}
else if(a[i]<a[j])
{
c[i]=max(c[i],c[j]+1);//动态的去写入在当前车质量下最大的上升子序列是多少。
}
}
sum=max(sum,c[i]+b[i]-1);//不同质量之间的比较
}
printf("%d\n",sum);
}
return 0;
}
本文介绍了一种火车调度算法,目标是在限定条件下将列车车厢按重量降序排列,形成最长的合法列车。通过动态规划求解最大上升子序列和最大下降子序列,确保每次车厢到达时能够最优地添加到列车头部或尾部。

735

被折叠的 条评论
为什么被折叠?



