hdu 2660 Accepted Necklace

题目连接

http://acm.hdu.edu.cn/showproblem.php?pid=2660

Accepted Necklace

Description

I have N precious stones, and plan to use K of them to make a necklace for my mother, but she won't accept a necklace which is too heavy. Given the value and the weight of each precious stone, please help me find out the most valuable necklace my mother will accept.

Input

The first line of input is the number of cases. 
For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace. 
Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight. 
The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.

Output

For each case, output the highest possible value of the necklace.

Sample Input

1
2 1
1 1
1 1
3

Sample Output

1

dfs。。

#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<set>
using std::max;
using std::sort;
using std::pair;
using std::swap;
using std::queue;
using std::multiset;
#define pb(e) push_back(e)
#define sz(c) (int)(c).size()
#define mp(a, b) make_pair(a, b)
#define all(c) (c).begin(), (c).end()
#define iter(c) decltype((c).begin())
#define cls(arr, val) memset(arr, val, sizeof(arr))
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for(int i = 0; i < (int)n; i++)
#define tr(c, i) for(iter(c) i = (c).begin(); i != (c).end(); ++i)
const int N = 30;
const int INF = 0x3f3f3f3f;
typedef unsigned long long ull;
struct Node {
int v, w;
}A[N];
bool vis[N];
int W, K, n, ans;
void dfs(int cur, int w, int v, int tot) {
if (tot == K) {
ans = max(ans, v);
return;
}
for (int i = cur; i < n; i++) {
if (!vis[i] && tot + 1 <= K && w + A[i].w <= W) {
vis[i] = true;
dfs(i + 1, w + A[i].w, v + A[i].v, tot + 1);
vis[i] = false;
}
}
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int t;
scanf("%d", &t);
while (t--) {
ans = -INF;
scanf("%d %d", &n, &K);
rep(i, n) {
vis[i] = false;
scanf("%d %d", &A[i].v, &A[i].w);
}
scanf("%d", &W);
dfs(0, 0, 0, 0);
printf("%d\n", ans);
}
return 0;
}
上一篇:POSTGRES与JDBC对照


下一篇:【MySQL】结构行长度的一些限制