题目
Avin has a string. He would like to uniform-randomly select four characters (selecting the same character is allowed) from it. You are asked to calculate the probability of the four characters being ”avin” in order.
Input
The first line contains n (1 ≤ n ≤ 100), the length of the string. The second line contains the string. To simplify the problem, the characters of the string are from ’a’, ’v’, ’i’, ’n’.
Output
Print the reduced fraction (the greatest common divisor of the numerator and denominator is 1), representing the probability. If the answer is 0, you should output “0/1”.
Sample Input
4
avin
4
aaaa
Sample Output
1/256
0/1
题目大意
输入一个长度n,然后输入一个长度为n的字符串(一组测试样例),问你在这个字符串中随机挑选四个排列为a v i n的概率(可重复挑选),如果为零输出0/1,否则输出最简化的分数形式概率。
解题思路
根据计算原理中的分步乘法原理,将读入字符串时或者读入字符串后,在字符串中统计字符a v i n的个数,分别记作 Na Nv Ni Nn。根据分步原理,第一个字符选到a有Na中情况,第二个字符选到v有Nv种可能,第三个字符选到i有Ni种可能,第四个字符选到n有Nn种可能,所以a v i n的可能数为 NaNvNi*Nn。而对于总情况,因为允许重复选择,所以每一个字符都有n种可能,所以总情况有nnn*n种可能。若NaNvNiNn=0则输出"0/1"\n,否则就直接输出:NaNvNiNn/G “/” nnn*n/G
G=gcd(NaNvNiNn,nnnn);
具体代码
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
return (b == 0) ? a : gcd(b, a % b);
}
int main()
{
int m;
while (scanf("%d",&m)!=EOF)
{
char arr[101];
int a = 0, v = 0, i = 0, n = 0;
scanf("%s", arr);
for (int j = 0; j < m; j++) {
if (arr[j] == 'a')
a++;
else if (arr[j] == 'v')
v++;
else if (arr[j] == 'i')
i++;
else if (arr[j] == 'n')
n++;
}
int x = m * m * m * m;
int sum = a * v * i * n;
if (sum == 0)printf("0/1\n");
else printf("%d/%d\n", sum / gcd(x, sum), x / gcd(x, sum));
}
return 0;
}