您的位置:首页 > 其它

USACO 1.1 friday

2010-10-24 21:30 106 查看
统计每月13号是星期几

Friday the Thirteenth

Is Friday the 13th really an unusual event?

That is, does the 13th of the month land on a Friday less often than on any other day of the week? To answer this question, write a program that will compute the frequency that the 13th of each month lands on Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday over a given period of N years. The time period to test will be from January 1, 1900 to December 31, 1900+N-1 for a given number of years, N. N is non-negative and will not exceed 400.

There are few facts you need to know before you can solve this problem:

* January 1, 1900 was on a Monday.

* Thirty days has September, April, June, and November, all the rest have 31 except for February which has 28 except in leap years when it has 29.

* Every year evenly divisible by 4 is a leap year (1992 = 4*498 so 1992 will be a leap year, but the year 1990 is not a leap year)

* The rule above does not hold for century years. Century years divisible by 400 are leap years, all other are not. Thus, the century years 1700, 1800, 1900 and 2100 are not leap years, but 2000 is a leap year.

Do not use any built-in date functions in your computer language.

Don't just precompute the answers, either, please.

PROGRAM NAME: friday

INPUT FORMAT

One line with the integer N.

SAMPLE INPUT (file friday.in)

20

OUTPUT FORMAT

Seven space separated integers on one line. These integers represent the number of times the 13th falls on Saturday, Sunday, Monday, Tuesday, ..., Friday.

SAMPLE OUTPUT (file friday.out)

36 33 34 33 35 35 34

]/*
ID: xdzhbin1
LANG: C++
TASK:friday
*/
#include <fstream>
#include <vector>
using namespace std;
//判断给定的年份是否为闰年
bool is_leap_year(int year)
{
if((year%4 == 0 && year%100 != 0) || year%400 == 0)
return true;
return false;
}
//给定年份和月份,返回当月的天数
int days_of_month(int year, int month)
{
if(month==4 || month==6 || month==9 || month==11)
return 30;
else if(month == 2 && is_leap_year(year))
return 29;
else if(month == 2 && !is_leap_year(year))
return 28;
else return 31;
}

//给定年份和月份,返回当月13号是星期几
//为了计算的简便,记录下上月13号是星期几,从上月有多少天很快就能算出这月13号是星期几
int week(int year, int month)
{
static int last = 6;	//1900年1月13号是星期六
if(year==1900 && month==1) return last;	//直接返回

int days; //上个月有多少天
if(month == 1)	//上个月是去年12月
{
days = days_of_month(year-1,12);
}
else
{
days = days_of_month(year,month-1);
}
last = (last + days)%7;	//从上月13号推出这月13号
return last;
}

int main()
{
ifstream in("friday.in",ios_base::in);
ofstream out("friday.out",ios_base::out);
int n_years;
in>>n_years;	//读入要计算的年份
int i,j;
vector<int> v(7,0);	//记录星期出现的天数,v[0]是星期天,v[1]是星期一,依次类推
for(i=1900; i<1900+n_years; i++)
{
for(j=1; j<=12; j++)
{
v[week(i,j)]++;		//统计
}
}
//输出,注意输出的格式
out<<v[6]<<" ";
for(i=0; i<5; i++)
out<<v[i]<<" ";
out<<v[5]<<endl;
//关闭文件流
in.close();
out.close();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: