hdu - 3959 Board Game Dice(数学)

来源:互联网 发布:沙迪克火花机怎样编程 编辑:程序博客网 时间:2024/05/17 07:20

这道题比赛中没做出来,赛后搞了好久才出来的,严重暴露的我薄弱的数学功底,

这道题要推公式的,,,有类似于1*a+2*a^2+3*a^3+...+n*a^n的数列求和。

最后画了一张纸才把最后的结果推出来。::(x*M^x)/N.

而且通过这道题我发现有些数学函数还不如直接循环来的快

例如这道题中求x的值的时候。

【我在此收回前面的话,昨天是oj的问题,今天我又交了一遍log的代码,耗时变成了0ms了。。。OMG】

方法一:

int x = int(log(n)/log(m)+0.5);
        if(_pow(m,x)<n) x += 1;

耗时15ms

方法二:

int x;
        for(x = 1; ; ++x)
            if(_pow(m,x)>=n)
                break;

耗时0ms


代码如下:

#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <queue>#include <stack>#include <map>#include <vector>#include <algorithm>#define LL long long#define M 10005#define N 15using namespace std;int n, m;LL _pow(LL a, LL b){    if(b==0) return 1;    LL ans = _pow(a,b/2);    if(b&1) return ans*ans*a;    else return ans*ans;}LL gcd(LL a, LL b){    return b==0?a:gcd(b,a%b);}int main (){    int t, k = 0;    scanf("%d",&t);    while(t--)    {        scanf("%d%d", &n, &m);        int x;        for(x = 1; ; ++x)            if(_pow(m,x)>=n)                break;        LL a = _pow(m,x)*x;        LL b = n;        LL g = a>b?gcd(a,b):gcd(b,a);        printf("Case %d: %I64d/%I64d\n", ++k, a/g, b/g);    }    return 0;}


原创粉丝点击