CF1209E Rotate Columns
http://codeforces.com/problemset/problem/1209/E2http://codeforces.com/problemset/problem/1209/E2这是一道最近 Codeforces 比赛的题目, 当时在场上昏昏欲睡, 连小的点都没有想出来, 现在再看一下.
题意
给你一个
分析
观察分析发现, 答案至少取到每列按照最大值排序的前
代码
可以用以下方法取
for (int k = s; ; k = (k - 1) & s) {
...
if (k == 0) break;
}用以下方法取
for (int k = s; k < (1 << n); k = (k + 1) | s) {
...
}#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <cassert>
#include <cmath>
using namespace std;
typedef long long int64;
const int INF = 0x3f3f3f3f;
const int MAXN = 14;
const int MAXS = (1 << 12) + 10;
const int MAXM = 2010;
int a[MAXN][MAXM];
int mxval[MAXM];
int dp[MAXN][MAXS];
int col[MAXM];
#include <cctype>
#include <cstdio>
template <typename T = int>
inline T read() {
T X = 0, w = 0;
char ch = 0;
while (!isdigit(ch))
{
w |= ch == '-';
ch = getchar();
}
while (isdigit(ch)) {
X = (X << 3) + (X << 1) + (ch ^ 48);
ch = getchar();
}
return w ? -X : X;
}
int val[MAXS]; // 预处理每次循环移位的结果
int main() {
int tcnt = read();
for (int T = 1; T <= tcnt; T++) {
int n = read();
int m = read();
memset(a, 0, sizeof a);
memset(col, 0, sizeof col);
memset(mxval, 0, sizeof mxval);
memset(dp, 0, sizeof dp);
for (int i = 0; i < n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] = read();
mxval[j] = max(mxval[j], a[i][j]);
}
}
for (int i = 1; i <= m; i++) {
col[i] = i;
}
sort(col + 1, col + m + 1, [](const int& a, const int& b) -> bool {
return mxval[a] > mxval[b];
});
for (int i = 1; i <= min(n, m); i++) {
memset(val, 0, sizeof val);
for (int s = 0; s < (1 << n); s++) {
for (int j = 0; j < n; j++) { // 暴力循环移位
int now = 0;
for (int k = 0; k < n; k++) {
if (s & (1 << k)) {
now += a[(j + k) % n][col[i]];
}
}
val[s] = max(val[s], now);
}
}
memset(dp[i], 0, sizeof dp[i]);
for (int s = 0; s < (1 << n); s++) {
for (int k = s; ; k = (k - 1) & s) {
dp[i][s] = max(dp[i][s], dp[i - 1][k] + val[s ^ k]);
// clog << dp[i][s] << ' ';
if (k == 0) break; // 至少执行一次
}
}
// clog << endl;
}
cout << dp[min(n, m)][(1 << n) - 1] << endl;
}
}