POJ 3666 Making the Grade(dp)

2926 단어
Making the Grade
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] {02차원 그룹은 이 문제를 통과할 수 있지만 메모리의 사용량이 매우 많기 때문에 스크롤 그룹으로 바꾸는 것이 더욱 적합하다.
코드는 다음과 같습니다.
#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; }



좋은 웹페이지 즐겨찾기