1. 程式人生 > >CCF 201503-3 節日

CCF 201503-3 節日

思路: 1. 首先計算每月的第一天是星期幾,據此推斷第 b 個星期 c 是否在該月內,不在就輸出 none。 2. 用基姆拉爾森計算公式判斷第 y 年第 m 月第 d 天是星期幾。用字串流處理輸出格式。 程式碼如下:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int caculateWeekDay(int y, int m, int d)  //根據年月日判斷星期幾 
{
    if(m == 1 || m == 2)
    {
        m += 12
; y--; } int iWeek = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7 + 1; return iWeek; } bool isLeapYear(int &y) //判斷是否是瑞年 { return (y%400 == 0 || (y%4 == 0 && y%100 != 0)); } string print(int y, int m, int d) //把年月日輸出為題目要求格式 { stringstream s1, s2, s3; string ys, ms, ds, result; s1 << y; s1 >> ys; s2 << m; s2 >> ms; s3 << d; s3 >> ds; if
(m < 10) ms = "0"+ms; if(d < 10) ds = "0"+ds; result = ys + "/" + ms + "/" + ds + "\n"; return result; } int main() { int a, b, c, y1, y2; int mon[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; cin >> a >> b >> c >> y1 >> y2; for(int y = y1; y <= y2; y++) { mon[2
] = isLeapYear(y) ? 29:28; //閏年2月29天 int week = caculateWeekDay(y, a, 1); //y年a月1號是星期 week int goal; //目標日期 if(c < week) goal = 1 + b*7 + c- week; //這個可以自己推一下 else goal = 1 + (b-1)*7 +c - week; if(goal > mon[a]) cout << "none\n"; else cout << print(y, a, goal); } return 0; }