本文共 1686 字,大约阅读时间需要 5 分钟。
为了解决这个问题,我们需要找到消灭所有狼的最小代价。每次消灭一只狼时,需要支付这只狼的a攻击力和它旁边的狼的b攻击力。消灭一只狼后,左右两边的狼会并在一起。我们需要找到最小代价。
#includeusing namespace std;ll read() { ll c = getchar(); ll Nig = 1; ll x = 0; while (!isdigit(c) && c != '-') { c = getchar(); } if (c == '-') { Nig = -1; c = getchar(); } while (isdigit(c)) { x = (x << 1) + (c - '0'); c = getchar(); } return Nig * x;}int main() { int T = read(); for (; T--; ) { int n = read(); vector a(n + 2), b(n + 2); for (int i = 1; i <= n; ++i) { a[i] = read(); b[i] = read(); } ll INF = 0x3f3f3f3f; vector > dp(n + 2, vector (n + 2, INF)); for (int i = 1; i <= n; ++i) { dp[i][i] = a[i] + (i > 1 ? b[i - 1] : 0) + (i < n ? b[i + 1] : 0); } for (int i = n - 1; i >= 1; --i) { for (int j = i + 1; j <= n; ++j) { ll temp1 = dp[i + 1][j] + a[i] + (i > 1 ? b[i - 1] : 0) + (j < n ? b[j + 1] : 0); ll temp2 = dp[i][j - 1] + a[j] + (i > 1 ? b[i - 1] : 0) + (j < n ? b[j + 1] : 0); dp[i][j] = min(temp1, temp2); } } cout << dp[1][n] << endl; }}
转载地址:http://uloo.baihongyu.com/