POJ - 1160 ios
思路:優化
平行四邊形不等式優化dpspa
dp[i][j]:前j個選i個做爲郵局的最小答案.net
w[i][j]:i到j之間選一個做爲郵局的最小距離和,確定是選中間的3d
dp[i][j] = min{dp[i-1][k] + w[k+1][j]}code
這個方程和石子歸併相似,知足四邊形不等式(通常打表找規律,不推不等式),因此決策變量知足決策單調性blog
假設s[i][j]爲dp[i][j]的最優決策變量k,則s[i-1][j] <= s[i][j] <= s[i][j+1]ci
因此j這一個維度從大到小get
代碼:string
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize(4) #include<iostream> #include<cstdio> #include<cstring> using namespace std; #define y1 y11 #define fi first #define se second #define pi acos(-1.0) #define LL long long #define LD long double //#define mp make_pair #define pb push_back #define ls rt<<1, l, m #define rs rt<<1|1, m+1, r #define ULL unsigned LL #define pll pair<LL, LL> #define pli pair<LL, int> #define pii pair<int, int> #define piii pair<int, pii> #define pdd pair<long double, long double> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); //head const int N = 305; int x[N], n, p; int dp[N][N], s[N][N], sum[N]; inline int cal(int l, int r) { int m = l+r >> 1; return (m-l+1)*x[m] - (sum[m]-sum[l-1]) + sum[r] - sum[m] - (r-m)*x[m]; } int main() { scanf("%d %d", &n, &p); for (int i = 1; i <= n; ++i) scanf("%d", &x[i]); for (int i = 1; i <= n; ++i) sum[i] = sum[i-1]+x[i]; mem(dp, 0x3f); dp[0][0] = 0; for (int i = 1; i <= p; ++i) { s[i][n+1] = n-1; for (int j = n; j >= 1; --j) { for (int k = s[i-1][j]; k <= s[i][j+1]; ++k) { if(k+1 <= j && dp[i-1][k]+cal(k+1, j) < dp[i][j]) { dp[i][j] = dp[i-1][k]+cal(k+1, j); s[i][j] = k; } } } } printf("%d\n", dp[p][n]); return 0; }
附打表代碼及結果