标签:
这题我特别愚蠢的把输入视为字符串,代码变得臃肿又繁琐
超时原因:给每个数打表,最后把区间内数相加,要是有多组很大的数,比如1~999987,4~777777……复杂度就是指数级
修改:表中每个元素i存储0~i的总个数
#include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; const int Max = 1000000; int a[Max]; int b[Max]; int main() { int x,y; memset(a,0,sizeof(a)); memset(a,0,sizeof(b)); for(int i = 125; i < 1000000; i++) { int m = 0; int n = 0; char s[8]; int cnt = 0; //itoa(i,s,10); //cout << s; int j = i; while(j > 0) { //这个错误也常犯 s[cnt] = j%10+‘0‘; j = j/10; // cout << j << endl; cnt ++; } int l = strlen(s); if(strstr(s,"5")&&strstr(s,"2")&&strstr(s,"1")) m++; if(strstr(s,"125")) n++; a[i] = a[i-1] + m; //记录0到i之间的521个数 b[i] = b[i-1] + n; // cout << b[i]; } int cn = 1; while(scanf("%d%d",&x,&y)==2) { int p = a[y] - a[x-1],q = b[y] - b[x-1]; printf("Case %d:%d %d\n",cn,p,q); cn++; } return 0; }
#include<stdio.h> int a[2][1000001]={0}; int main() { int k=0,i,sum=0; for(i=1;i<=1000000;i++) { if((i%10==5||(i/10)%10==5||(i/100)%10==5||(i/1000)%10==5||(i/10000)%10==5||(i/100000)%10==5)&&(i%10==2||(i/10)%10==2||(i/100)%10==2||(i/1000)%10==2||(i/10000)%10==2||(i/100000)%10==2)&&(i%10==1||(i/10)%10==1||(i/100)%10==1||(i/1000)%10==1||(i/10000)%10==1||(i/100000)%10==1)) {sum++; if(i/1000==521||(i/100)%1000==521||(i/10)%1000==521||i%1000==521)k++;} a[0][i]+=sum; a[1][i]+=k; } int m,n,w=0; while(scanf("%d%d",&n,&m)!=EOF) printf("Case %d:%d %d\n",++w,a[0][m]-a[0][n-1],a[1][m]-a[1][n-1]); }
标签:
原文地址:http://www.cnblogs.com/ekinzhang/p/4402692.html