求助,不开O2全TLE,开O2全RE

P1591 阶乘数码

zhibuba @ 2020-05-26 23:03:26

#include <stdio.h>
#include <string.h>

#define SIZE 1000

typedef char INT[SIZE];

void mul(INT a, int b, INT c)
{
    memset(c, 0, sizeof(INT));
    for (int i = SIZE - 1; i >= 0; i--)
    {
        int tmp = a[i] * b;
        int j = i;
        while (tmp > 0)
        {
            c[j--] = tmp % 10;
            tmp /= 10;
        }
    }
}

void fac(int n, INT a)
{
    INT b, c;
    memset(b, 0, sizeof(INT));
    b[SIZE - 1] = 1;
    memset(c, 0, sizeof(INT));
    char * t1 = b, * t2 = c, * tmp = NULL;
    while (n)
    {
        mul(t1, n--, t2);
        tmp = t1, t1 = t2, t2 = tmp;        
    }
    memcpy(a, t1, sizeof(INT));
}

int count(INT a, int c)
{
    int ans = 0, i;
    for (i = 0; i < SIZE - 1 && a[i] == 0; i++)
        ;
    while (i < SIZE)
    {
        if (a[i++] == c)
            ans++;
    }
    return ans; 
}

int main(void)
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int n, c;
        scanf("%d%d", &n, &c);
        INT a;
        fac(n, a);
        printf("%d\n",count(a, c));
    }
    return 0;
}

by SamariumPhosphide @ 2020-05-26 23:13:51

码风鬼畜


by WanderOvO @ 2020-05-27 10:02:58

您代码连简单的数据都过不了,比如7!=5040,而您的程序表示没有出现5;8!=40320,但是您的程序表示8!中只有一个0。建议别先考虑O_2了,先通过这俩例子检查程序的基本功能是否正确


by shijihong @ 2020-09-29 13:45:10

一段更简单的代码

#include <iostream>
using namespace std;
int main(){
    int t;
    int result(int x,int y);
    cin>>t;
    int resl[t];
    for(int i=0;i<=t-1;i++){
        int m,n;
        cin>>m>>n;
        resl[i]=result(m,n);
    }
    for (int i=0;i<=t-1;i++) cout<<resl[i]<<endl;
}
int result(int x,int y){
    int a[1000];
    for (int i=0;i<1000;i++) a[i]=0; 
    a[999]=1;
    for (int i=1;i<=x;i++){
        for (int j=0;j<1000;j++)
            a[j]*=i;
        for (int k=999;k>=0;k--){
            if (a[k]>9){
                a[k-1]+=a[k]/10;
                a[k]-=(a[k]/10)*10;
            }
        }
    }
    int zeroplace=0;
    while (a[zeroplace]==0) zeroplace++;
    int res=0;
    for (int i=zeroplace;i<=999;i++)
        if(a[i]==y) res++;
    return res;

}

by shijihong @ 2020-09-29 13:46:13

不过我那段代码在洛谷上就tle,在本机上瞬间出答案


|