您的位置:首页 > 其它

hdu 2842 Chinese Rings

2016-06-01 11:07 316 查看

Chinese Rings

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 837 Accepted Submission(s):
480


[align=left]Problem Description[/align]
Dumbear likes to play the Chinese Rings (Baguenaudier).
It’s a game played with nine rings on a bar. The rules of this game are very
simple: At first, the nine rings are all on the bar.
The first ring can be
taken off or taken on with one step.
If the first k rings are all off and the
(k + 1)th ring is on, then the (k + 2)th ring can be taken off or taken on with
one step. (0 ≤ k ≤ 7)

Now consider a game with N (N ≤ 1,000,000,000)
rings on a bar, Dumbear wants to make all the rings off the bar with least
steps. But Dumbear is very dumb, so he wants you to help him.

[align=left]Input[/align]
Each line of the input file contains a number N
indicates the number of the rings on the bar. The last line of the input file
contains a number "0".

[align=left]Output[/align]
For each line, output an integer S indicates the least
steps. For the integers may be very large, output S mod 200907.

[align=left]Sample Input[/align]

1
4
0

[align=left]Sample Output[/align]

1
10

[align=left]Source[/align]
2009
Multi-University Training Contest 3 - Host by WHU

[align=left]Recommend[/align]
gaojie | We have carefully selected several similar
problems for you: 2841 2844 2843 2840 2839

根据题意推理。设f
表示拆掉前n个环需要的步数
显然要先把前n-2个拿掉:f[n-2]
拿掉第n个:1步
剩下第n-1个,如果要拆它,那么第n-2个必须挂着,根据题目意思,需要把前n-2个再次挂上,接下来的就是f[n-1]
f
= 2 * f[n - 2] + f[n - 1] + 1
然后推出系数矩阵,矩阵快速幂即可
| 1 0 0| | 1 | | 1 |
| 0 0 1| * | f[n-2] | = |f[n-1]|
| 1 2 1| | f[n-1] | | f
|

题意:如果前k个环被拆掉,第k+1个还被挂着,那么第k+2个就可以拿下或者装上,1可以任意挂取,按照这个要求取下所有的环。

附上代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#define mod 200907
using namespace std;
struct mat
{
long long m[3][3];
};

mat mul(mat a,mat b)
{
mat c;
int i,j,k;
memset(c.m,0,sizeof(c.m));
for(i=0; i<3; i++)
for(j=0; j<3; j++)
{
for(k=0; k<3; k++)
c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
c.m[i][j]%=mod;
}
return c;
}

mat product(mat a,int k)
{
if(k==1)  return a;
else if(k&1) return mul(product(a,k-1),a);
else return product(mul(a,a),k/2);
}

int main()
{
int n,m,i,j;
mat a,b;
int x[4]= {1,1,2};
while(~scanf("%d",&n)&&n)
{
if(n<3)
{
printf("%d\n",x
%mod);
continue;
}
memset(a.m,0,sizeof(a.m));
a.m[0][0]=1;
a.m[1][2]=1;
a.m[2][0]=1;
a.m[2][1]=2;
a.m[2][2]=1;
b=product(a,n-2);
long long ans=0;
for(i=0; i<3; i++)
ans+=(b.m[2][i]*x[i])%mod;
printf("%I64d\n",ans%mod);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: