HEU OJ 1040: 09/03 : Accepted

2 views
Skip to first unread message

小山

unread,
Sep 3, 2006, 11:29:29 AM9/3/06
to ju_...@googlegroups.com
我和赵欣苹,秦海龙一起做的一道题:
In how many ways can you choose k elements out of n elements, not taking order into account?
Write a program to compute this number.

Input

The input will contain one or more test cases.
Each test case consists of one line containing two integers n (n >= 1) and k (0 <= k <= n).
Input is terminated by two zeroes for n and k.

Output

For each test case, print one line containing the required number. This number will always fit into an integer, i.e. it will be less than 2^31.

Sample Input

4 2
10 5
49 6
0 0

Sample Output

6
252
13983816

题目比较好懂(说这话我该脸红,我读了好久啊-_-!),就是编写求解组合的程序。
 
最后通过的代码如下:

//题目:HEU OJ 1040
//时间:2006/09/03
//参与:牛晋 赵欣苹 秦海龙

#include <stdio.h>
#include <stdlib.h>

int out_of(int,int);

int main()
{
    int n,k,result;
   
    while(scanf("%d%d",&n,&k) != EOF){
    if(n==0 && k==0) break;
    if(k>n/2)  k = n-k;
    if(k == 0) {
        printf("1\n");
        continue;
    }
    if(k == 1) {
            printf("%d\n",n);
        continue;
    }
       
    result=out_of(n, k);

        printf("%d\n",result);
       
    }

   return 0;
}

int out_of(int n, int k)
{
    int  n_tmp = n+1-k;
    long long result = 1;

    for(int k_tmp = 1; k_tmp <= k; k_tmp++){
        result *= n_tmp;
    //if(result % k_tmp != 0)  printf(" Error ");
    result /= k_tmp;
    ++n_tmp;
    }
   
    return  result;
}



--
Discover the design of nature, discover the evidence of God.

小山

unread,
Sep 3, 2006, 11:43:23 AM9/3/06
to ju_...@googlegroups.com
编写的过成很容易呵,但是调试让我们快疯了啊!主要错误如下:


int out_of(int n, int k)
{
    int  n_tmp = n+1-k;
    int  result = 1;    //<==看这里^_^
    ... ...

虽然题目保证结果是可以被int保存的,不会溢出。但是计算过程却可能超出int的最大值,我们的算法是边乘边除的方式计算,以为这样就可以保证变量result不会溢出。
提交结果后总是提示:Wrong Answer
 
我和海龙一起死脑筋认为输出数据格式有问题,拼命尝试各种方式输出。-_-!
只需将result定义为 :
long long result就可以避免计算时溢出了。
Reply all
Reply to author
Forward
0 new messages