ZOJ ——3827 Information Entropy

来源:互联网 发布:线切割制图软件 编辑:程序博客网 时间:2024/05/22 17:50

题意:题目给出一个求熵公式:然后编写程序实现该公式运算。

解题思路:本题关键点是所给的Pi值为所有Pi之和的百分比,故要得到公式中的p(x),还需进行Pi/100的运算。然后可按照公式进行编写,注意:在遇到0的时候,不进行处理,因为0*log(p0) = 0;此外还要注意c语言中log函数的运用。

Code:

#include <iostream>#include <cmath>#include <cstdio>using namespace std;int array[110];int main(){   //freopen("input.txt","r",stdin);   int T,N;   scanf("%d",&T);   while(T--)   {       char S[5];       scanf("%d %s",&N,&S);       for(int i = 0; i < N; i++)        scanf("%d",&array[i]);        double ans = 0;        if(S[0] == 'b')        {            for(int i = 0; i < N; i++)            {               if(!array[i]) continue;               ans +=(1.0*array[i]/100)*log2(array[i]*1.0/100);            }        }       if(S[0] == 'n')        {            for(int i = 0; i < N; i++)            {               if(!array[i]) continue;               ans +=(1.0*array[i]/100)*log(array[i]*1.0/100);            }        }        if(S[0] == 'd')        {            for(int i = 0; i < N; i++)            {               if(!array[i]) continue;               ans +=(1.0*array[i]/100)*log10(array[i]*1.0/100);            }        }        printf("%.12lf\n",-ans);   }   return 0;}

0 0
原创粉丝点击