dfs注意最优解不一定是从1节点开始 所以要枚举每个节点
#include<bits/stdc++.h>
using namespace std;
const int N = 21;
int ans[N];
int res;
int a[N];
int b[N][N];
int n;
int cnt;
int A[N];
int s;
void dfs(int i , int sum)
{
if(sum > res)
{
for(int l = 0 ; l <= cnt ; l++) A[l] = ans[l];
res = sum;
s = cnt;
}
for(int t = i + 1 ; t <= n ; t++)
{
if(b[i][t])
{
ans[++cnt] = t;
dfs(t,sum+a[t]);
cnt--;
}
}
}
int main()
{
scanf("%d",&n);
for(int i = 1 ; i <= n ; i++)
{
scanf("%d",&a[i]);
}
int T = n;
int m = n-1;
for(int i = 1 ; i <= m ; i++)
{
for(int j = i + 1 ; j <= T ; j++)
{
cin>>b[i][j];
}
}
for(int i = 1 ; i <= n ; i++)
{
ans[cnt] = i;
dfs(i,a[i]);
}
for(int i = 0 ; i <= s ; i++) cout<<A[i]<<" ";
cout<<'\n'<<res;
return 0;
}
递推 记录一下每个点的前缀 最后输出最大值的那条路
#include<bits/stdc++.h>
using namespace std;
const int N = 21;
int ans[N];
int a[N];
int b[N][N];
int n,p;
int f[N];
int res;
void print(int x)
{
if(ans[x] != 0) print(ans[x]);
cout<<x<<" ";
}
int main()
{
scanf("%d",&n);
for(int i = 1 ; i <= n ; i++)
{
scanf("%d",&a[i]);
}
int m = n-1;
for(int i = 1 ; i <= m ; i++)
{
for(int j = i + 1 ; j <= n ; j++)
{
cin>>b[i][j];
}
}
//f[1] = a[1];
for(int i = 1 ; i <= n ; i++)
{
f[i] = a[i];
for(int j = i - 1 ; j >= 0 ; j--)
{
if(b[j][i])
{
if(f[j] + a[i] > f[i])
{
f[i] = f[j] + a[i];
ans[i] = j;
}
}
}
if(f[i] > res)
{
res = f[i];
p = i;
}
}
print(p);
cout<<'\n'<<res;
return 0;
}