2015编程之美资格赛A

本文介绍了一种高效计算两个特定日期间闰年数量的方法,通过数学公式快速得出结果,避免了不必要的枚举操作,并提供了完整的C++实现代码。

题目链接:

http://hihocoder.com/contest/msbop2015qual/problem/1

分析:

大数据为10^9,其实仔细考虑不需要任何的枚举,年份再大也不是特殊的,前一个年份记为year1,后一个记为year2,考虑从公元元年到year1-1的年份中包含的2.29,计算公式为(year1-1)/4-(year1-1)/100+(year1-1)/400,然后再计算出公元元年到year2-1中包含的2.29,两者相减。然后需要特殊考虑一下year1和year2这两年。

具体代码。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
map<string,int> mp;
int get_month(char s[])
{
    string str;
    for(int i=0;i<(int)strlen(s);i++)
        str.push_back(s[i]);
    return mp[str];
}
int main()
{
    mp["January"]=1;mp["February"]=2;mp["March"]=3;mp["April"]=4;mp["May"]=5;mp["June"]=6;mp["July"]=7;mp["August"]=8;mp["September"]=9;mp["October"]=10;mp["November"]=11;mp["December"]=12;
    //freopen("in.txt","r",stdin);
    int t;
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
        char month1[20],month2[20];
        int m1,m2,day1,year1,day2,year2;
        scanf("%s %d, %d",month1,&day1,&year1);
        scanf("%s %d, %d",month2,&day2,&year2);
        m1=get_month(month1);
        m2=get_month(month2);
        year1--;//求从1年到year1之前的一年一共有多少闰年
        year2--;
        int res1=year1/4-year1/100+year1/400;
        int res2=year2/4-year2/100+year2/400;
        if((((year2+1)%4==0&&(year2+1)%100!=0)||(year2+1)%400==0)&&(m2>=3||(m2==2&&day2==29))) res2++;//如果year2这一年是闰年而且过了闰月 则res2++
        if((((year1+1)%4==0&&(year1+1)%100!=0)||(year1+1)%400==0)&&(m1>=3)) res2--;  //如果这一年是闰年 但是日期在2.29之后,则1到(year2-1)年多算了一次
        printf("Case #%d: %d\n",i,res2-res1);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值