2016多校训练Contest7: 1011 Knights hdu5819

来源:互联网 发布:php个人简历源代码 编辑:程序博客网 时间:2024/04/30 22:50

Problem Description
At the start of this game, there are N knights on a road of length N+1. The knights are numbered from 1 to N, and the ith knight stands i unit from the left end of the road.

When the game begins, each knight moves to left or right at the same speed. Whenever a knight reaches to the end of the road, he instantly changes his direction. 

Whenever two knights meet, they fight until one loses, where each one of them wins in 50% possibility. Then the winner keeps moving in the direction he was moving before the fight, and the loser quits the game. The fighting time is very short and can be ignored.

The game continues until only one knight remains, and that knight is the winner.

Now, we know the moving direction of each knight initially. Can you calculate the possibility that Nth knight win the game?
 

Input
The first line of the input gives the number of test cases T (T <= 10). In each test case, the first line is an integer N (1 <= N <= 1000). The second line contains N integers. The ith integer represents the ith knight’s moving direction, and 0 stands for left while 1 stands for right.
 

Output
Each test case contains one line and one integer. Let’s assume the possibility be equal to the irreducible fraction P / Q. Print the value of PQ1 in the prime field of integers modulo 1 000 000 007(109+7). It is guaranteed that this modulo does not divide Q, thus the number to be printed is well-defined.
 

Sample Input
220 030 1 0
 

Sample Output
Case #1: 500000004Case #2: 250000002


在考场上只想出了n^3的做法。。其实n^2的做法就多一个小优化。。

首先因为只要求第n个骑士的胜利概率,而每个骑士速度一样说明没有追及问题

所以我们只要求出有多少个骑士向右走的概率就可以了

用f[i][j]表示前i个人有j个人向右的概率

f[i][j]=f[i-1][j-1]*1/2+f[i-1][j-2]*1/4+……

我一开始推出来的是一个这样的式子,转移是n^3的

观察这个式子不难发现。f[i][j]=f[i][j+1]*1/2+f[i-1][j]*1/2

这样我们就把复杂度降成n^2的了

#include<map>#include<cmath>#include<queue>#include<vector>#include<cstdio>#include<string>#include<cstring>#include<iostream>#include<algorithm>using namespace std;long long mod=1000000007;inline long long power(long long x,int y){int xx=1;while(y!=0){if(y%2==1)xx=xx*x%mod;x=x*x%mod;y=y/2;}return xx;}int a[100001];long long f[1001][1001];int main(){//freopen("1011.in","r",stdin);//freopen("1011.ans","w",stdout); long long tx=power(2,mod-2);int T,k=0;scanf("%d",&T);while(T>0){T--;k++;int n;scanf("%d",&n);int i,j;for(i=1;i<=n;i++)scanf("%d",&a[i]);memset(f,0,sizeof(f));f[1][1]=1;for(i=2;i<=n;i++){if(a[i]==0||i==n){for(j=i-1;j>=1;j--)f[i][j]=f[i-1][j];for(j=i-1;j>=2;j--){f[i][j-1]=(f[i][j-1]+f[i][j]*tx%mod)%mod;f[i][j]=f[i][j]*tx%mod;}}else{for(j=1;j<=i;j++)f[i][j]=f[i-1][j-1];}}long long ans=f[n][1]*tx%mod;printf("Case #%d: %I64d\n",k,ans);}return 0;}


0 0
原创粉丝点击