ACM难度选择问题

版权声明:如有帮助,赞一个可好。邮箱:[email protected] https://blog.csdn.net/qq_40946921/article/details/89739966

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;

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/89739966