AcWing 282. 石子合并. (Javascript)
原题链接
简单
作者:
cp777
,
2021-03-05 21:02:41
,
所有人可见
,
阅读 339
const N = 310;
let f = [];
for (let i = 0; i < N; i++) f[i] = new Int32Array(N);
let s = new Int32Array(N);
let n = 0;
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
} else if (lineIdx === 1) {
let arr = getInputNums(line);
for (let i = 0; i < n; i++) s[i + 1] = arr[i];
for (let i = 1; i < n; i++) s[i + 1] += s[i]; //前缀和
for (let len = 2; len <= n; len++) { //枚举堆个数,一堆默认为0,从2堆开始
for (let i = 1; i + len - 1 <= n; i++) { //所有堆
let l = i, //左端点
r = i + len - 1; //右端点
f[l][r] = 1e8; //设置较大的数,因为一会要取最小值
for (let k = l; k < r; k++) { //分界线k
f[l][r] = Math.min(f[l][r], f[l][k] + f[k + 1][r] + s[r] - s[l - 1]);
}
}
}
console.log(f[1][n]);
}
});
});