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
题意:
要求字符串只有a,v,i,n四种字母,每次随机取四个,问取得avin的概率
a,v,i,n的概率是a,v,i,n出现的次数/字符串的长度的四次方
但是输出结果时需要约分,例如2/256,你要输出1/128。
思路:
这道题我是先全部遍历一遍,用a、v、i、n分别计算出’a’、 ‘v’、 ‘i’、 'n’四个字符出现的次数。然后判断是否这四个字符都出现过,如果没有出现过,直接输出0/1,四个字符都出现过的话,就算出
一共四个位置;每个位置可以有n种放法: q = N*N*N*N,成功方案数:p = a*v*i*n;记得需要约分。
代码如下:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
char b[105];
int gcd(int a,int b)
{
if (b==0)return a;
return gcd(b,a%b);
}
int main()
{
int N;
while(cin>>N)
{
int a=0,v=0,i=0,n=0;//分别统计四个字母出现的次数
for(int j=0;j<N;j++)//遍历统计
{
cin>>b[j];
if(b[j]=='a')
{
a++;
}
else if(b[j]=='v')
{
v++;
}
else if(b[j]=='i')
{
i++;
}
else if(b[j]=='n')
{
n++;
}
}
if(N>=4)
{
if(a!=0&&v!=0&&i!=0&&n!=0)
{
int p=a*v*i*n,q=N*N*N*N;
int sum=gcd(p,q);
printf("%d/%d\n",p/sum,q/sum);
}
else printf("0/1\n");
}
else printf("0/1\n");
}
return 0;
}