HDU 1757 A Simple Math Problem 题解与分析

A Simple Math Problem

Time Limit: 3000/1000 MS (Java/Others)    

Memory Limit: 32768/32768 K (Java/Others)

【题目大意】:

        一个方程f(x),式子如下定义:

        如果 x < 10,那么 f(x) = x.
        如果 x >= 10 ,那么f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
        并且ai(0<=i<=9) 只可能是 0 或 1 .

        现在,给定a0~a9,和整数k,m,现在想让你求 f(k)%m.

【分析】:

        小于10时直接输出。大于10时分析式子f(x)=a0*f(x-1)+a1*f(x-2)+a2*f(x-3)+……+a9*f(x-10),转化的构造矩阵为                                             

|01 0 ......... 0|    |f0|  |f1 |
|0 0 1 0 ....... 0|    |f1|  |f2 |
|................1| |..| = |...|
|a9 a8 .........a0|    |f9|  |f10|
                 

如样例一转化为:                                            

0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1                                  

发现只需将构造矩阵自乘K-9次即可出现需要的那一个,这里可以用快速幂的思想来做这一步操作,即矩阵自乘快速幂优化

【代码】:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define MAX 11
struct mat{int c[MAX][MAX];};
mat a;
int K,P,ans=0;
mat mult(mat A,mat B)
{
      mat now;
      for(int i=1;i<=10;i++)
            for(int j=1;j<=10;j++)
            {
                  now.c[i][j]=0;
                  for(int k=1;k<=10;k++)
                        now.c[i][j]=(now.c[i][j]+A.c[i][k]*B.c[k][j])%P;
            }
      return now;
}
mat power(mat now,int n)
{
      if(n==1)   return now;
      else if(n&1)
            return mult(power(now,n-1),now);
      else 
      {
            mat use;
            use=power(now,n/2);
            return mult(use,use);
      }
}
void work()
{
      mat now;
      ans=0;
      now=power(a,K-9);
      for(int i=1;i<=10;i++)
            ans=(ans+now.c[10][i]*(i-1))%P;//这里的i-1即f(0-9) 
}
int main()
{
      //freopen("input.in","r",stdin);
	  //freopen("output.out","w",stdout); 
	  while(scanf("%d%d",&K,&P)!=EOF)
	  {
            for(int i=10;i>=1;i--)
                  scanf("%d",&a.c[10][i]);
            if(K<10)   {printf("%d\n",K%P);continue;}
            for(int i=1;i<10;i++)//建立构造矩阵 
            {
                  for(int j=1;j<=10;j++)
                  {
                        if(j==i+1)   a.c[i][j]=1;
                        else a.c[i][j]=0;
                  }
            }
            work();
            printf("%d\n",ans);
      }
	  //system("pause");
      return 0;
}


 

转载注明出处:http://blog.csdn.net/u011400953


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值