NC24878. [USACO 2009 Ope S]Grazing2
描述
输入描述
* Line 1: Two space-separated integers: N and S
* Lines 2..N+1: Line i+1 contains the single integer: Pi
输出描述
* Line 1: A single integer: the minimum total distance the cows have to travel. This number is guaranteed to be under 1,000,000,000 (thus fitting easily into a signed 32-bit integer).
示例1
输入:
5 10 2 8 1 3 9
输出:
4
说明:
Cows move from stall 2 to 3, 3 to 5, and 9 to 10. The total distance moved is 1 + 2 + 1 = 4. The final positions of the cows are in stalls 1, 3, 5, 8, and 10.C++11(clang++ 3.9) 解法, 执行用时: 15ms, 内存消耗: 12380K, 提交时间: 2019-08-05 18:40:21
#include<iostream> #include<cmath> #include<algorithm> using namespace std; int num[1750],dp[1750][1750],n,s,d; int main(){ while(cin>>n>>s){ for(int i=1;i<=n;i++) cin>>num[i]; d=(s-1)/(n-1); sort(num+1,num+1+n); for(int i=0;i<1750;i++){ for(int j=0;j<1750;j++){ dp[i][j]=1e7; } } dp[1][1]=num[1]-1; for(int i=2;i<=n;i++){ for(int j=1;j<=i&&j<=s-(n-1)*d;j++){ dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+abs(num[i]-(i-1)*d-j); } } cout<<dp[n][s-(n-1)*d]; } return 0; }
C++14(g++5.4) 解法, 执行用时: 14ms, 内存消耗: 16200K, 提交时间: 2019-08-16 16:47:43
#include<bits/stdc++.h> using namespace std; const int N=2e3+5; int a[N],f[N][N],n,m,d; int main() { scanf("%d%d",&n,&m);m--; d=m/(n-1); for(int i=1;i<=n;i++)scanf("%d",&a[i]),a[i]--; sort(a+1,a+n+1); memset(f,63,sizeof f); f[1][0]=a[1]; for(int i=2;i<=n;i++) for(int j=0;j<=min(i-1,m-d*(n-1));j++) f[i][j]=min(f[i-1][j],f[i-1][j-1])+abs(a[i]-((i-1)*d+j)); printf("%d",f[n][m-d*(n-1)]); }