ZOJ3950统计

来源:互联网 发布:知乎评价章泽天长相 编辑:程序博客网 时间:2024/06/05 08:03

how many 9s will appear in all the dates between Y1-M1-D1 and Y2-M2-D2 (both inclusive)


#include <stdio.h>#include <string>#include <stdlib.h>bool isLeapYear(int y){    return (y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0));}int getYearDayNines(int y){    int _y = y, dig = 0, totol = 0 ;    while(_y > 0)    {        dig += (_y % 10 == 9 ? 1 : 0) ;        _y /= 10 ;    }    totol = dig * 365 + 3 * 11 + 2 + 30 ;    if(isLeapYear(y))    {        totol += dig + 1 ;    }    return totol ;}int monthDay[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } ;int getMonthDays(int y, int m){    if(isLeapYear(y) && m == 2) return monthDay[2] + 1  ;    else return monthDay[m] ;}int getNine(int y, int m, int d){    int sum = 0;    while (y > 0)    {        sum += (y % 10 == 9 ? 1 : 0);        y /= 10;    }    while (m > 0)    {        sum += (m % 10 == 9 ? 1 : 0);        m /= 10;    }    while (d > 0)    {        sum += (d % 10 == 9 ? 1 : 0);        d /= 10;    }    return sum;}int between(int fy, int fm, int fd, int ty, int tm, int td){    int sum = 0 ;    if(fm == tm)    {        for(int d = fd ; d <= td ; d++)            sum += getNine(fy, fm, d) ;    }    else    {        for(int d = fd ; d <= getMonthDays(fy, fm) ; d++)            sum += getNine(fy, fm, d) ;        for(int d = 1 ; d <= td ; d++)            sum += getNine(fy, tm, d) ;        if(fm + 1 < tm)        {            int md = getNine(fy, 0, 0) ;            for(int m = fm + 1 ; m < tm ; m++)            {                sum +=  md * getMonthDays(fy, m) ;                if(m == 9)                    sum += getMonthDays(fy, m) ;                sum += 3 ;                if(m == 2 && ! isLeapYear(fy)) sum-- ;            }        }        return sum ;    }    return sum ;}int yearMonths[10000], sumYearMonths[10000] ;void init(){    sumYearMonths[1999] = 0 ;    for(int y = 2000 ; y <= 9999 ; y++)    {        yearMonths[y] = getYearDayNines(y) ;        sumYearMonths[y] = sumYearMonths[y-1] + yearMonths[y] ;    }}int sum(int fy, int fm, int fd, int ty, int tm, int td){    if(fy == ty) return between(fy, fm, fd, ty, tm, td) ;    if(fy + 1 == ty)        return between(fy, fm, fd, fy, 12, 31) + between(ty, 1, 1, ty, tm, td) ;    int sum = 0 ;    sum += sumYearMonths[ty-1] - sumYearMonths[fy] ;    sum += between(fy, fm, fd, fy, 12, 31) + between(ty, 1, 1, ty, tm, td) ;    return sum ;}int main(){    init() ;    int t,  fy,  fm,  fd,  ty,  tm,  td ;    scanf("%d", &t) ;    while(t--)    {        scanf("%d%d%d%d%d%d", &fy,  &fm,  &fd,  &ty,  &tm, &td) ;        printf("%d\n", sum(fy,  fm,  fd, ty,  tm, td)) ;    }    return 0;}


0 0
原创粉丝点击