HDU - 1171 Big Event in HDU(母函数、0-1背包)

    xiaoxiao2021-08-26  86

    题目:

    Description

    Nowadays, we all know that Computer College is the biggest department in HDU. But, maybe you don't know that Computer College had ever been split into Computer College and Software College in 2002.  The splitting is absolutely a big event in HDU! At the same time, it is a trouble thing too. All facilities must go halves. First, all facilities are assessed, and two facilities are thought to be same if they have the same value. It is assumed that there is N (0<N<1000) kinds of facilities (different value, different kinds). 

    Input

    Input contains multiple test cases. Each test case starts with a number N (0 < N <= 50 -- the total number of different facilities). The next N lines contain an integer V (0<V<=50 --value of facility) and an integer M (0<M<=100 --corresponding number of the facilities) each. You can assume that all V are different.  A test case starting with a negative integer terminates input and this test case is not to be processed. 

    Output

    For each case, print one line containing two integers A and B which denote the value of Computer College and Software College will get respectively. A and B should be as equal as possible. At the same time, you should guarantee that A is not less than B. 

    Sample Input

    2 10 1 20 1 3 10 1 20 2 30 1 -1

    Sample Output

    20 10 40 40

    母函数方法

    这个题目,用母函数的思路做,或者用0-1背包的思路做,方法都是一样的,操作也都是差不多的,时间上没什么差别。

    代码:

    #include<stdio.h> int num[51], r[127505], sum; void f() { for (int i = 0; i <= sum / 2; i++)r[i] = (i == 0); for (int i = 1; i <= 50; i++)if (num[i]) for (int j = sum / 2; j >= 0; j--)if (r[j]) for (int k = i; k<=i*num[i] && k + j <= sum / 2; k += i)r[k + j] += r[j]; int k = 0; for (int i = sum / 2; i >= 0; i--)if (r[i]) { k = i; break; } printf("%d %d\n", sum - k, k); } int main() { int n, v, m; while (scanf("%d",&n)) { if (n <= 0)break; for (int i = 0; i <= 50; i++)num[i] = 0; sum = 0; while (n--) { scanf("%d%d", &v, &m); num[v] = m; sum += v*m; } f(); } return 0; }

    这个代码AC了,没什么问题。

    之前少了一句k<=i*num[i],就是f函数里面的3层循环的最内层的循环,k的终止条件少了这一个。

    这样导致结果自然是错误的,但是在OJ里面的结果是超时。

    想了半天不知道为什么超时,测试了一下:

    输入:

    10 50 100 49 100 48 100 47 100 46 100 45 100 44 100 43 100 42 100 41 100

    计算的时间比较长,大约就是1秒。

    然后仔细检查代码,才发现是少了k<=i*num[i]

    因为少了这一句,所以在时间上会多很多。

    其实很多题目都是这样,因为忽略了一个细节,导致计算错误不说,计算时间还多了很多很多。

    转载请注明原文地址: https://ju.6miu.com/read-677162.html

    最新回复(0)