24h購物| | PChome| 登入
2012-02-29 08:08:31| 人氣1,461| 回應0 | 上一篇 | 下一篇

[UVA] 11456 - Trainsorting

推薦 0 收藏 0 轉貼0 訂閱站台

Problem A: Trainsorting

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 Specification

The first line is the number of test cases to follow. The test cases follow, one after another; the format of each test case is the following:

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.

Sample Input

1
3
1
2
3

Output Specification

Output a single integer giving the number of cars in the longest train that can be made with the given restrictions.

Output for Sample Input

3


做法 : DP
O(nlogn), max(LIS[i]+LDS[i]-1);

#include <stdio.h>
#include <stdlib.h>
void findLIS(int N, int LIS[], int pos[], int A[]) {
int i, L = -1, l, r, m, newSet;
int j;
for(i = 0; i < N; i++) {
l = 0, r = L, newSet = -1;
while(l <= r) {
m = (l+r)/2;
if(pos[m] <= A[i]) {
if(m == L || pos[m+1] > A[i]) {
newSet = m+1;break;
} else
l = m+1;
} else {
r = m-1;
}
}
if(newSet == -1) newSet++;
pos[newSet] = A[i];
LIS[i] = newSet+1;
if(L < newSet) L = newSet;
}
}
void findLDS(int N, int LDS[], int pos[], int A[]) {
int i, L = -1, l, r, m, newSet;
int j;
for(i = 0; i < N; i++) {
l = 0, r = L, newSet = -1;
while(l <= r) {
m = (l+r)/2;
if(pos[m] >= A[i]) {
if(m == L || pos[m+1] < A[i]) {
newSet = m+1;break;
} else
l = m+1;
} else {
r = m-1;
}
}
if(newSet == -1) newSet++;
pos[newSet] = A[i];
LDS[i] = newSet+1;
if(L < newSet) L = newSet;
}
}
int main() {
int T, N, i;
int A[2001], LDS[2001], LIS[2001], pos[2001];
scanf("%d", &T);
while(T--) {
scanf("%d", &N);
for(i = 0; i < N; i++)
scanf("%d", &A[N-i-1]);
findLIS(N, LIS, pos, A);
findLDS(N, LDS, pos, A);
int max = 0;
for(i = 0; i < N; i++) {
if(LIS[i]+LDS[i]-1 > max)
max = LIS[i]+LDS[i]-1;
}
printf("%d\n", max);
}
return 0;
}

台長: Morris
人氣(1,461) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 193 - Graph Coloring
此分類上一篇:[UVA] 10827 - Maximum sum on a torus

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文