#include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); const long long MAX = 281474976710655LL; int n, i, j, k; long long cur, min; cin >> n; long long **tab = new long long*[n]; for (i = 0; i < n; ++i) { tab[i] = new long long[n-i]; for (j = 0; j < n-i; ++j) cin >> tab[i][j]; } /* for (i = 0; i < n; ++i) { for (j = 0; j < n-i; ++j) cout << tab[i][j] << ' '; cout << endl; } */ for (j = 1; j < n; ++j) { for (i = 0; i < n-j; ++i) { min = MAX; for (k = 0; k < j; ++k) { cur = tab[i][k] + tab[i+k+1][j-k-1]; if (cur < min) min = cur; } cur = tab[i][j] + std::min(tab[i][j-1], tab[i+1][j-1]); if (cur < min) min = cur; if (j > 1) { cur = tab[i][j-2] + tab[i][j]; if (cur < tab[i][j-1]) tab[i][j-1] = cur; cur = tab[i+2][j-2] + tab[i][j]; if (cur < tab[i+1][j-1]) tab[i+1][j-1] = cur; } tab[i][j] = min; } } cout << tab[0][n-1] << '\n'; /* for (i = 0; i < n; ++i) { for (j = 0; j < n-i; ++j) cout << tab[i][j] << ' '; cout << endl; } */ }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); const long long MAX = 281474976710655LL; int n, i, j, k; long long cur, min; cin >> n; long long **tab = new long long*[n]; for (i = 0; i < n; ++i) { tab[i] = new long long[n-i]; for (j = 0; j < n-i; ++j) cin >> tab[i][j]; } /* for (i = 0; i < n; ++i) { for (j = 0; j < n-i; ++j) cout << tab[i][j] << ' '; cout << endl; } */ for (j = 1; j < n; ++j) { for (i = 0; i < n-j; ++i) { min = MAX; for (k = 0; k < j; ++k) { cur = tab[i][k] + tab[i+k+1][j-k-1]; if (cur < min) min = cur; } cur = tab[i][j] + std::min(tab[i][j-1], tab[i+1][j-1]); if (cur < min) min = cur; if (j > 1) { cur = tab[i][j-2] + tab[i][j]; if (cur < tab[i][j-1]) tab[i][j-1] = cur; cur = tab[i+2][j-2] + tab[i][j]; if (cur < tab[i+1][j-1]) tab[i+1][j-1] = cur; } tab[i][j] = min; } } cout << tab[0][n-1] << '\n'; /* for (i = 0; i < n; ++i) { for (j = 0; j < n-i; ++j) cout << tab[i][j] << ' '; cout << endl; } */ } |