离散化+dp
本来退役了之后就不打算怎么花时间在写题上了,今天休息时闲逛发现一道以前看过的有趣的题,傻乎乎的想了十几分钟,终于才看出这个题的解法。可见有些东西一日不用,就下降半米,两日不用,下降十米,三日不用,疑是银河落九天。
这道题的解决方法直接想出来是很困难的,需要先观察,再猜测,验证猜测无误后基于猜测来解决问题。最关键的一点猜测是每个沙堆的最终高一定在所有沙堆的初始高度中出现过。这个猜测的验证我是脑补了几个样例验证的。这一点明确了以后,就可以dp了,dp[i][j]记录到第i个沙堆时,当前最高沙堆的高度h[j](之所以不是j是因为高度需要离散化处理,因为高度数量的范围远大于沙堆的数量范围,j表示离散化后第j高的高度)。然后转移方程也能很简单的列出来了。
想出来以后想找找有谁做出来这题,结果发现早就A过这题了,现在一点印象也没有了。领会了一个道理,题是写不完的,不要在意写题的结果,更多的去关注写题的过程,可能长久的收获会更大一些。欲速则不达啊。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int mod=19970303;
int n,m;
ll h[3002];
int r[3002],top[3002];//f高度排行数组,用于间接排序
ll fabs(ll a){
return a>0?a:-a;
}
struct Sand{
ll hi;
int od;
}sand[3002];
ll dp[3002][3002];
bool cmp(Sand a,Sand b){
return a.hi<=b.hi;
}
int get_rank(){
int cnt=1;
r[sand[1].od]=cnt;//最矮的
h[1]=sand[1].hi;
for(int i=2;i<=n;i++){
h[i]=sand[i].hi;
if(sand[i].hi>sand[i-1].hi)cnt++;
r[sand[i].od]=cnt;
}
unique(h+1,h+n+1);
return cnt;
}
ll get_ans(){
ll minans=9223372036854775807;
for(int j=1;j<=m;j++){
if(dp[n][j]<minans) minans=dp[n][j];
}
return minans%mod;
}
void print_dp(){
for(int j=1;j<=m;j++){
cout<<h[j]<<": ";
for(int i=1;i<=n;i++)
cout<<dp[i][j]<<' ';
cout<<endl;
}
}
int main(){
//freopen("data.txt","r",stdin);
//freopen("test.txt","w",stdout);
ios::sync_with_stdio(false);
while(cin>>n){
for(int n0=1;n0<=n;n0++){
cin>>sand[n0].hi;
sand[n0].od=n0;
}
sort(sand+1,sand+n+1,cmp);
m=get_rank();
for(int j=1;j<=m;j++){
top[j]=r[1];
if(h[j]<h[r[1]]){
dp[1][j]=((fabs(h[j]-h[r[1]])));
top[j]=j;
}
else dp[1][j]=0;
}
for(int i=2;i<=n;i++)
for(int j=1;j<=m;j++){
if(h[r[i]]>h[j]){
dp[i][j]=((fabs(h[j]-h[r[i]])+dp[i-1][j]));
top[j]=max(j,top[j]);
}
else if(h[r[i]]<=h[top[j]]) dp[i][j]=((fabs(h[top[j]]-h[r[i]])+dp[i-1][j]));
else if(h[r[i]]>h[top[j]]){
dp[i][j]=dp[i-1][j];
top[j]=max(r[i],top[j]);
}
if(j>1){
if(dp[i][j]>dp[i][j-1]){
dp[i][j]=dp[i][j-1];
top[j]=top[j-1];
}
}
}
cout<<get_ans()<<endl;
//print_dp();
}
return 0;
}