[POJ 3666] S - Making the Grade

首先对高度大小进行排序,d[i][j]表示第i个修改为第j大最少的消耗,dp[i][j] 由dp[i - 1][k] 更新,(1<=k<= j)
代码如下:

#include<iostream>
#include<algorithm>
#include<vector>
#define debug(x) cout<<#x<<" is "<<x<<endl
#define pb push_back 
using namespace std;
typedef long long ll;
ll ans = (1LL<<60);
const int N = 2000 + 5;
ll dp[N][N];
int a[N];

int n;
vector<int> b;
int main(){
    
    

	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n;
	for(int i = 1;i <= n;i++){
    
    
		cin>>a[i];
		b.pb(a[i]);		
	}
	sort(b.begin(),b.end());
	b.erase(unique(b.begin(),b.end()),b.end());
	int len = b.size();

	for(int j = 1;j <= len;j++){
    
    	
		dp[1][j] = abs(b[j - 1] - a[1]);
	}
	for(int i = 2;i <=n;i++){
    
    
		ll tmp = (1LL<<60);
		for(int j = 1;j <= len;j++){
    
    
			tmp = min(tmp,dp[i - 1][j]);//选取tmp其实挺巧妙的
			dp[i][j] = tmp + abs(b[j - 1] - a[i]);
		}
	}
	for(int i = 1;i <= len;i++)ans = min(ans,dp[n][i]);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_20252251/article/details/108410892