ACM难度选择问题

Problem Description
LL is very sensitive to the difficulty of ACM problems. He can assign each problem a positive integer from [1,10000000] to denote its difficulty ( although he has only ACed about 1000 problems ^_^ ). Now, there are N problems in his mind. He want to choose some of them to hold a contest and the total difficulty of all problems in the contest is as near as possible to M.

Input
For each case, the first line is two positive integers N and M (1<=N<=26). Followed by N lines. Each line contains the problem's ID ( a single capital letter ) and its difficulty.

Output
For each case, ouput how many and which problems he should choose in the format of the sample. If more than one combinations of problems reach the request, output the one which comes earliest in lexicography order.

Sample Input
3 10
A 4
B 12
C 8

Sample Output
2
A C

#include<stdio.h>
#include<math.h>
int dfc[27] = { 0 }, top = -1, visited[27] = { 0 }, sum = 0, n, m;
char stk[30],res[30];
int mindfs=10000001;
void dfs(int i) {
    for (int j = 0; j < 26; ++j) {
        if (dfc[j] && !visited[j]) {
            visited[j] = 1;
            sum += dfc[j];
            stk[++top] = 'A' + j;
            if (abs(sum - m) < mindfs) {
                mindfs = abs(sum - m);
                for (int k = 0; k <= top; k++)
                    res[k] = stk[k];
                res[top+1] = '\0';
            }
            dfs(j);
            --top;
            sum -= dfc[j];
            visited[j] = 0;
        }
    }
}
int main() {
    char ch;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; ++i) {
        getchar();
        scanf("%c", &ch);
        scanf("%d", &dfc[ch-'A']);
    }
    dfs(27);
    printf("%d\n", mindfs);
    for (char* ch = res; *ch != '\0'; ++ch)
        printf("%s%c", ch == res ? "" : " ", *ch);
    return 0;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值