F - String
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
思路:
先找出能获得的总的可选择次数,因为都是要从所给的字符串中选四个字符,所以可以使用pow(m,4)函数,求得分母。
然后依次遍历找出四个字符出现的次数:’a’, ’v’, ’i’, ’n’,然后根据排序规则,及四个字符出现的次数相乘即可得出分子。
因为要约分,所以利用辗转相除法(gcd函数)求出分子和分母的最大公约数,随后根据题意输出即可。
实现代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int main()
{
int m;
char b[105];
while(~scanf("%d%s",&m,b))
{
int a=0,v=0;
int i=0,n=0;
int mu=0,fi=0;
mu=pow(m,4);
for(int j=0;j<m;j++)
{
if(b[j]=='a')
a++;
if(b[j]=='v')
v++;
if(b[j]=='i')
i++;
if(b[j]=='n')
n++;
}
fi=a*v*i*n;
int ss=gcd(fi,mu);
fi=fi/ss;
mu=mu/ss;
if(fi==0)
printf("0/1\n");
else
printf("%d/%d\n",fi,mu);
}
}