暴搜
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000005;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false);
int n;
int bom[25];
int path[25];
int tmp[25];
int Max;
int P;
int lnk[25][25];
void dfs(int pos, int x, int sum) {
if (Max < sum) {
for (int i = 1; i <= pos; i++) {
path[i] = tmp[i];
}
P = pos;
Max = sum;
}
for (int i = x + 1; i <= n; i++) {
if (lnk[x][i]) {
tmp[pos + 1] = i;
dfs(pos + 1, i, sum + bom[i]);
}
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", bom + i);
}
for (int i = 1; i <= n - 1; i++) {
for (int j = i + 1; j <= n; j++) {
scanf("%d", &lnk[i][j]);
}
}
for (int i = 1; i <= n; i++) {
tmp[1] = i;
dfs(1, i, bom[i]);
}
for (int i = 1; i <= P; i++) {
printf("%d ", path[i]);
}
printf("\n%d", Max);
return 0;
}
DP解法
可以回想一下最长子序列
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000005;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false);
int n;
int bom[25];
int dp[25];
int pre[25];
int lnk[25][25];
int ans = 0;
int pos;
void to_print_path(int x) {
if (pre[x])
to_print_path(pre[x]);
printf("%d ", x);
}
void solve() {
dp[1] = bom[1];
for (int i = 2; i <= n; i++) {
dp[i] = bom[i];
for (int j = i - 1; j > 0; j--) {
if (lnk[j][i]) {
if (dp[i] < dp[j] + bom[i]) {
dp[i] = dp[j] + bom[i];
pre[i] = j;
}
}
}
if (ans < dp[i]) {
ans = dp[i];
pos = i;
}
}
to_print_path(pos);
printf("\n%d", ans);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", bom + i);
}
for (int i = 1; i <= n - 1; i++) {
for (int j = i + 1; j <= n; j++) {
scanf("%d", &lnk[i][j]);
}
}
solve();
return 0;
}