1、刚开始觉得无从下手,仔细考虑后发现其实只要遍历每一天,然后让星期数周而复始,遇到13就加一,再加一个对于闰年的判断即可。
/*
ID:mrxy564
PROG:friday
LANG:C++
*/
#include <cstdio>
#include <cstring>
using namespace std;
int mon[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int weekday[8]={0};
bool is_leap_year(int i){
if(i%100==0&&i%400==0) return true;
if(i%100!=0&&i%4==0) return true;
return false;
}
int main()
{
freopen("friday.in","r",stdin);
freopen("friday.out","w",stdout);
int N,count;
while(scanf("%d",&N)==1){
memset(weekday,0,sizeof(weekday));
count=3;
for(int i=1;i<=N;i++){
if(is_leap_year(1900+i-1))
mon[2]=29;
else mon[2]=28;
for(int j=1;j<=12;j++)
for(int k=1;k<=mon[j];k++){
if(k==13){
weekday[count]++;
}
if(count==7) count=1;
else count++;
}
}
for(int i=1;i<=7;i++)
if(i!=7)
printf("%d ",weekday[i]);
else
printf("%d\n",weekday[i]);
}
return 0;
}
官方题解:
Brute force is a wonderful thing. 400 years is only 4800 months, so it is perfectly practical to just walk along every month of every year, calculating the day of week on which the 13th occurs for each, and incrementing a total counter.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> int isleap(int y) { return y%4==0 && (y%100 != 0 || y%400 == 0); } int mtab[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; /* return length of month m in year y */ int mlen(int y, int m) { if(m == 1) /* february */ return mtab[m]+isleap(y); else return mtab[m]; } void main(void) { FILE *fin, *fout; int i, m, dow, n, y; int ndow[7]; fin = fopen("friday.in", "r"); fout = fopen("friday.out", "w"); assert(fin != NULL && fout != NULL); fscanf(fin, "%d", &n); for(i=0; i<7; i++) ndow[i] = 0; dow = 0; /* day of week: January 13, 1900 was a Saturday = 0 */ for(y=1900; y<1900+n; y++) { for(m=0; m<12; m++) { ndow[dow]++; dow = (dow+mlen(y, m)) % 7; } } for(i=0; i<7; i++) { if(i) fprintf(fout, " "); fprintf(fout, "%d", ndow[i]); } fprintf(fout, "\n"); exit(0); }
官方题解没有枚举每一天,更加简单。