AcWing 1341.十三号星期五

题解:十三号星期五

题目描述

在这里插入图片描述

题目链接:
https://www.acwing.com/problem/content/1343/

思路分析

  1. 两种思路:一个是按月份枚举按天枚举

  2. 按月份枚举
    在这里插入图片描述

  3. 按天枚举
    从1900.1.1开始枚举,13号就++,月数过12,year++,week过周天就day++

代码实现

按月份枚举

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};//定义13个正好下标就和月份对上

int weekday[7];//0是周一,1是周二......

int main()
{
    int n;
    cin>>n;
    int days=0;//当前1月1号距离1900年1月1号过了多少天
    for(int year=1900;year<1900+n;year++)
    {
        for(int i=1;i<=12;i++)
        {
            weekday[(days+12)%7]++;
            days+=month[i];//这个月13号的星期几的编号
            if(i==2)
            {
                if( year%100&&year%4==0||year%400==0)
                   days++;
            }
        }
    }
    for(int i=5,j=0;j<7;i=(i+1)%7,j++)
    cout<<weekday[i]<<' ';
    cout<<endl;
    
    return 0;
          
}

按天枚举

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  // 打表
int weekday[7];

int get(int year, int m)
{
    if (m != 2) return months[m];
    if (year % 100 && year % 4 == 0 || year % 400 == 0)
        return 29;
    return 28;
}

int main()
{
    int n;
    cin >> n;

    int week = 0;
    int year = 1900, month = 1, day = 1;
    while (year < 1900 + n)
    {
        if (day == 13) weekday[week] ++ ;
        week = (week + 1) % 7;
        day ++ ;
        if (get(year, month) < day) 
        month ++, day = 1;
        if (month > 12) 
        month = 1, year ++ ;
    }

    for (int i = 5, j = 0; j < 7; i = (i + 1) % 7, j ++ )
        cout << weekday[i] << ' ';
    cout << endl;

    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值