首先,这题dfs暴搜太low,数据一大就tle
其次如果你对dp不熟练,并且此题还要求保存路径,更加难
这时候选择记忆化搜索特别棒!!(其实是自己dp太垃圾)
(记忆化搜索就是反写dp,复杂度一样的)
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <map>
#include <math.h>
#include <cstring>
#include <string.h>
#include <queue>
#define ll long long
#include<set>
using namespace std;
inline int read() {
int k = 0, f = 1; char ch = getchar();
while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { k = k * 10 + ch - '0'; ch = getchar(); }return k * f;
}
int w[25];
vector<int>ve[25];
int ans[25];
int ind[105];
int dfs(int x)
{
if (ans[x])return ans[x];
for (int i = 0; i < ve[x].size(); i++)
{
int val = dfs(ve[x][i]) + w[x];
if (val > ans[x])
{
ans[x] = val;
ind[x] = ve[x][i];
}
}
if (ans[x] == 0)
{
ind[x] = x;
return ans[x] = w[x];
}
return ans[x];
}
int main()
{
int n = read();
for (int i = 1; i <= n; i++)w[i] = read();
for (int i = 1; i <= n - 1; i++)
{
for (int j = i+1; j <= n; j++)
{
int t=read();
if (t == 1)ve[i].push_back(j);
}
}
for (int i = 1; i <= n; i++)
{
if (ans[i] == 0)ans[i]=dfs(i);
}
int out = 0;
int beg;
for (int i = 1; i <= n; i++)
{
if (ans[i] > out)
{
out = ans[i];
beg = i;
}
}
while (ind[beg] != beg)
{
cout << beg << ' ';
beg = ind[beg];
}
cout << beg << '\n';
cout << out << '\n';
}