银河

SKYIV STUDIO

  博客园 :: 首页 :: 博问 :: 闪存 :: :: :: 订阅 订阅 :: 管理 ::
  268 随笔 :: 2 文章 :: 2616 评论 :: 140万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
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   银河  阅读(736)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示