dp HDU - 5074

时间:2022-09-04 20:43:33

按题意推表达式

#include<cstdio>
#include<cstring>
#define max(a, b) (a)>(b)?(a):(b) int dp[][], num[][], a[]; int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = ; i <= m;++i)
for (int j = ; j <= m; ++j)
scanf("%d", &num[i][j]);
for (int i = ; i <= n; ++i)scanf("%d", &a[i]);
for (int i = ; i <= n; ++i)
{
if (a[i - ] > && a[i] > )dp[i][a[i]] = dp[i - ][a[i - ]] + num[a[i - ]][a[i]];
else if (a[i - ]< && a[i]>)
{
for (int k = ; k <= m; ++k)
dp[i][a[i]] = max(dp[i][a[i]], dp[i - ][k] + num[k][a[i]]);
}
else if (a[i - ] > && a[i] < )
{
for (int k = ; k <= m; ++k)
dp[i][k] = max(dp[i][k], dp[i - ][a[i - ]] + num[a[i - ]][k]);
}
else
{
for (int k = ; k <= m;++k)
for (int j = ; j <= m; ++j)
dp[i][k] = max(dp[i][k], dp[i - ][j] + num[j][k]);
}
}
int ans = ;
for (int i = ; i <= m; ++i)
ans = max(ans, dp[n][i]);
printf("%d\n", ans);