a574簡單年內序號對7取餘數
CPE:Doom’s Day Algorithm (UVa 12019)
把2011年的日期換成距離已知星期的日數。
解題思路
2011不是閏年,二月固定28天。將給定日期轉成從1月1日起算的零起點日數day=前面月份總天數+D−1。日期每增加一天,星期也向後一格,因此只需要day對7取餘數。
由題目已知4月4日星期一可回推1月1日星期六;以Monday到Sunday編號0..6,1月1日偏移為5,答案為week[(day+5)%7]。預先保存十二個月長即可,不用套用一般年份的複雜曆法公式。每筆只印完整英文星期名,不加Case標籤。
Step-by-step animation
示意:2011年1月1日、1月3日、1月8日
步驟 1 / 3
基準日
1月1日day=0,(0+5)%7=5,Saturday。
day0
索引5
- 星期
- Saturday
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
vector<int> month{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
vector<string> week{"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
int t;
cin >> t;
while (t--) {
int m, d;
cin >> m >> d;
int day = d - 1;
for (int i = 0; i < m - 1; ++i)
day += month[i];
cout << week[(day + 5) % 7] << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。