银河

SKYIV STUDIO

  博客园 :: 首页 :: 博问 :: 闪存 :: :: :: 订阅 订阅 :: 管理 ::
Timus 1402. Cocktails 要求计算出鸡尾酒共有多少种调法。

1402. Cocktails

Time Limit: 1.0 second
Memory Limit: 16 MB

Henry Shaker works as a barman in the favorite pub of Vito Maretti. Every evening he pleases the gangster with a new cocktail: vodka and Martini, gin and orange juice, kefir and mineral water. Vito pays generously for each new cocktail, but if the barman repeats a cocktail he is in trouble: Vito may shoot him. So Henry wants to know how soon he will have to leave the town. In order to know this you are to count how many different cocktails he can make having N components. A cocktail is the mixture of two or more components. Unfortunately, Henry can’t use one component more than once in the same cocktail. Nevertheless 'vodka and Martini' and 'Martini and vodka' are two different cocktails.

Input

The first input line contains an integer N (1 ≤ N ≤ 21) — an amount of components.

Output

an integer number of possible cocktails.

Sample

inputoutput
3
12
Problem Author: Sergey Pupyrev
Problem Source: The 12th High School Pupils Collegiate Programming Contest of the Sverdlovsk Region (October 15, 2005)

解答如下:

 1 using System;
 2 
 3 namespace Skyiv.Ben.Timus
 4 {
 5   // http://acm.timus.ru/problem.aspx?space=1&num=1402
 6   sealed class T1402
 7   {
 8     static void Main()
 9     {
10       int n = int.Parse(Console.ReadLine());
11       decimal m = 0, p = n;
12       for (int i = n - 1; i > 0; p *= i, m += p, i--) ;
13       Console.WriteLine(m);
14     }
15   }
16 }

这道题目是说,给定 N (1 ≤ N ≤ 21) 种不同的原料,要求计算出总共能够调制出多少种不同的鸡尾酒。每种原料最多只能使用一次,但是投放原料的次序不同调制出来的鸡尾酒也不同。

这其实是一个非常简单的组合数学问题,只要计算出使用 2 种、3 种、...、N 种不同原料能够调制出多少种不同的鸡尾酒就行了。答案如下:

P( N, 2 ) + P( N, 3 ) + ... + P( N, N )

这里,P( n, m ) 表示从 n 个不同的物品中任意取出 m 个的排列数,公式是:

P( n, m ) = n! / (n - m)! = n * (n - 1) * ... * (n - m + 1)

有了计算公式,写出相应的程序来就非常简单了。要注意的是,当 N = 21 时,答案约等于 1.4 x 1020。而 ulong.MaxValue = 264 - 1 ≈ 1.8 x 1019,所以如果使用 C/C++ 语言,看来只好使用 BigInteger 类了。还好 C# 语言的 decimal.MaxValue = 296 - 1 ≈ 7.9 x 1028,能够满足计算要求。

下面是本程序的 C++ 语言版本(用了点小技巧,没有使用 BigInteger 类):

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5   long long n, m = 0;
 6   std::cin >> n;
 7   if (n == 21return (std::cout << "138879579704209680000"), 0;
 8   for (long long p = n, i = n - 1; i > 0; p *= i, m += p, i--) ;
 9   std::cout << m;
10 }

posted on 2008-07-10 09:36  银河  阅读(725)  评论(0编辑  收藏  举报