题意
给定 \(n\) 个物品,任意分组,\(i\) 与 \(j\) 物品在同一组贡献为 \(a_{i, j}\)。
求最大贡献。\(n \le 16\)。
Sol
考虑状压 \(f_i\) 表示 \(i\) 集合的最大贡献。
注意到枚举最后一个选的数不好转移,考虑用一个集合转移到另一个集合。
子集枚举即可。
复杂度 \(3^n\)。
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#define int long long
using namespace std;
#ifdef ONLINE_JUDGE
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;
#endif
int read() {
int p = 0, flg = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flg = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
p = p * 10 + c - '0';
c = getchar();
}
return p * flg;
}
void write(int x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9) {
write(x / 10);
}
putchar(x % 10 + '0');
}
const int N = 21, M = 1e6 + 5;
array <array <int, N>, N> G;
array <int, M> f, g;
signed main() {
int n = read();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
G[i][j] = read();
for (int T = 0; T < 1 << n; T++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (!(T & (1 << (i - 1))) || !(T & (1 << (j - 1)))) continue;
g[T] += G[i][j];
}
}
}
for (int T = 0; T < 1 << n; T++) {
f[T] = g[T];
for (int P = (T - 1) & T; P; P = (P - 1) & T)
f[T] = max(f[T], f[T ^ P] + f[P]);
}
write(f[(1 << n) - 1]), puts("");
return 0;
}
标签:DPU,int,Grouping,long,array,include,getchar
From: https://www.cnblogs.com/cxqghzj/p/17850857.html