有N个物品,每个物品都有五种参数,现在要从中选K种,每种参数的数值是K种中对应的最大值,求五种参数的最大和。
一开始想了很久的0-1背包,可是空间不够= =
也有想到压缩状态,但是不知道压缩了然后怎么办= =
然后就参考了hcbbt巨巨(http://blog.csdn.net/hcbbt/article/details/35614265)
因为最后的最大值肯定是某一组或者某几组中产生的,所以可以记录31种状态的最大值,然后DFS。
真是奇妙的思路。
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <cmath>
#define LL long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const int MAXN = 10000 + 10;
const int MOD = 1e9 + 7;
typedef pair<int, int> pii;
typedef vector<int>::iterator viti;
typedef vector<pii>::iterator vitii;
int num[MAXN][5], sum[50], tmpMax[10];
int DFS(int S, int cntRem)
{
if (cntRem == 0) return 0;
int ret = 0;
for (int S0 = S; S0; S0 = (S0 - 1) & S)
ret = max(ret, sum[S0] + DFS(S ^ S0, cntRem - 1));
return ret;
}
int main()
{
//ROP;
int T, i, n, k, j;
scanf("%d", &T);
while (T--)
{
MS(tmpMax, 0); MS(sum, 0);
scanf("%d%d", &n, &k);
for (i = 0; i < n; i++)
for (j = 0; j < 5; j++)
{
scanf("%d", &num[i][j]);
tmpMax[j] = max(tmpMax[j], num[i][j]);
}
if (k >= 5)
{
int ans = 0;
for (i = 0; i < 5; i++) ans += tmpMax[i];
printf("%d\n", ans);
continue;
}
for (i = 0; i < n; i++)
for (int state = 0; state < (2 << 5); state++)
{
int tmp = 0;
for (j = 0; j < 5; j++)
if ((1 << j) & state) tmp += num[i][j];
sum[state] = max(sum[state], tmp);
}
printf("%d\n", DFS((1 << 5) - 1, k));
}
return 0;
}