FZU 2037

六月ゝ 毕业季﹏ 提交于 2020-02-04 12:28:20

                          Maximum Value Problem

Let’s start with a very classical problem. Given an array a[1…n] of positive numbers, if the value of each element in the array is distinct, how to find the maximum element in this array? You may write down the following pseudo code to solve this problem:

function find_max(a[1…n])

max=0;

for each v from a

if(max<v)

max=v;

return max;

However, our problem would not be so easy. As we know, the sentence ‘max=v’ would be executed when and only when a larger element is found while we traverse the array. You may easily count the number of execution of the sentence ‘max=v’ for a given array a[1…n].

Now, this is your task. For all permutations of a[1…n], including a[1…n] itself, please calculate the total number of the execution of the sentence ‘max=v’. For example, for the array [1, 2, 3], all its permutations are [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1]. For the six permutations, the sentence ‘max=v’ needs to be executed 3, 2, 2, 2, 1 and 1 times respectively. So the total number would be 3+2+2+2+1+1=11 times.

Also, you may need to compute that how many times the sentence ‘max=v’ are expected to be executed when an array a[1…n] is given (Note that all the elements in the array is positive and distinct). When n equals to 3, the number should be 11/6= 1.833333.

 Input

The first line of the input contains an integer T(T≤100,000), indicating the number of test cases. In each line of the following T lines, there is a single integer n(n≤1,000,000) representing the length of the array.

 Output

For each test case, print a line containing the test case number (beginning with 1), the total number mod 1,000,000,007

and the expected number with 6 digits of precision, round half up in a single line.

 Sample Input

2 2 3

 Sample Output

Case 1: 3 1.500000
Case 2: 11 1.833333
 
解题方法:推公式  第一个答案公式f(n) = (n-1)!+f(n-1)+(n-1)*f(n-1);       第二个答案公式 f(n) = f(n-1)+1/n;
3个数的排列:
123
132
213
231
312
4个数的排列可以看成在3个数排列的基础上添加一位,则4可以放在第一,第二,第三,第四位
①如果放在最后一位则有 (4-1)! 个
1234
1324
2134
2314
3124
3214
②如果是放在第一,第二和第三时则有 (4-1)*f(4-1);
4123   1423   1243
4132   1432   1342
4213   2413   2143
4231   2431   2341
4312   3412   3142
4321   3421   3241 
所以依此类推 就可以得到 公式f(n) = (n-1)!+f(n-1)+(n-1)*f(n-1)
至于第二个公式f(n) = f(n-1)+1/n  可以把上面那个公式除以一个n! 化简一下就可以得到。
代码:

#include <stdio.h>
#define ll __int64
#define MAX 1000005
#define MOD 1000000007
ll f[MAX]; //存放
ll jc[MAX];//
double tt[MAX];
int main()
{
 int t,n,i;
 f[1] = 1;
 jc[1] = 1;
 tt[1] = 1.0;
 for( i = 2 ; i < MAX ; i++)
 {
  jc[i] = (jc[i-1]*i) % MOD;
  f[i] = (jc[i-1] + i*f[i-1]) % MOD;
  tt[i] = tt[i-1] + 1.0/i;
 }
 scanf("%d",&t);
 for( i = 1 ; i <= t ; i++)
 {
  scanf("%d",&n);
  printf("Case %d: ",i);
  printf("%I64d %.6lf\n",f[n],tt[n]);
 }
 return 0;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!