POJ 3666 Making the Grade(dp)
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 5207
Accepted: 2455
Description
A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).
You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is
|A1 - B1| + |A2 - B2| + ... + |AN - BN |
Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.
Input
* Line 1: A single integer: N * Lines 2..N+1: Line i+1 contains a single integer elevation: Ai
Output
* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.
Sample Input
7
1
3
2
4
5
3
9
Sample Output
3
제목: n개의 숫자의 서열을 제시하여 임의의 숫자의 값을 수정하여 엄격하게 증가하지 않거나 엄격하게 감소하지 않는 서열로 만들 수 있습니다. 최소한의 수정량은 얼마입니까?
문제풀이: 왼쪽 나무라니, 이산화dp는 모두 할 수 없다(;′⌒`).dp도 어려워서 밤새 입문 문제를 봤어요.자, 본론으로 돌아가자.이 문제는 엄격하게 증가하지 않거나 엄격하게 감소하지 않는 상황에서 dp를 이용하여 해답을 구하는 데 차이가 없다.
pp[i][j]는 전 i+1개의 숫자에 대해 첫 번째 j개의 작은 숫자가 서열의 마지막 요소일 때의 최소 수정량을 나타낸다.
문제에서 제시한 원 서열에 따라 우리는 원소 간의 크기 관계를 확정하고 대응하는 번호는 p[i]이다.
dp[i][j] = min( dp[i-1][k] {0
코드는 다음과 같습니다.
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define ll __int64
using namespace std;
ll a[2020],b[2020];
ll dp[2][2020];
int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;++i)
{
scanf("%I64d",&a[i]);
b[i]=a[i];
}
sort(b,b+n);
for(i=0;i<n;++i)
dp[0][i]=abs(a[1]-b[i]);
for(i=1;i<n;++i)
{
ll temp=dp[(i-1)%2][0];
for(j=0;j<n;++j)
{
temp=min(dp[(i-1)%2][j],temp);
dp[i%2][j]=temp+abs(a[i]-b[j]);
}
}
ll ans=dp[(n-1)%2][0];
for(i=0;i<n;++i)
ans=min(ans,dp[(n-1)%2][i]);
printf("%I64d
",ans);
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.