Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 4446 Accepted Submission(s): 1551
php
#define _CRT_SECURE_NO_DepRECATE #define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <iostream> #include <cmath> #include <iomanip> #include <string> #include <algorithm> #include <bitset> #include <cstdlib> #include <cctype> #include <iterator> #include <vector> #include <cstring> #include <cassert> #include <map> #include <queue> #include <set> #include <stack> #define ll long long #define INF 0x3f3f3f3f #define ld long double const ld pi = acos(-1.0L), eps = 1e-8; int qx[4] = { 0,0,1,-1 }, qy[4] = { 1,-1,0,0 }, qxx[2] = { 1,-1 }, qyy[2] = { 1,-1 }; using namespace std; struct node { ll point, price; }classes[5000]; bool cmp(node x, node y) { return x.point < y.point; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; ll dp[5000][2]; while (cin >> n) { memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; i++) { cin >> classes[i].point >> classes[i].price; } sort(classes, classes + n, cmp);//題目沒說按照順序輸入,因此須要先排序 dp[0][1] = classes[0].price; dp[0][0] = INF; for (int i = 1; i < n; i++) { dp[i][1] = classes[i].price + min(dp[i - 1][0], dp[i - 1][1]); dp[i][0] = INF; ll m = 0; for (int f = i - 1; f >= 0; f--)//枚舉出i店鋪左邊第一個店鋪爲哪一個店鋪的時候花費最少,從i-1開始枚舉 { m += (i - f) * (classes[f + 1].point - classes[f].point);//重點,可畫圖理解,m爲每次往前推一點的時候增長的距離花費 dp[i][0] = min(dp[i][0], dp[f][1] + m); } } cout << min(dp[n - 1][0], dp[n - 1][1]) << endl; } return 0; }