试题编号: | 201503-3 |
试题名称: | 节日 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述
有一类节日的日期并不是固定的,而是以“a月的第b个星期c”的形式定下来的,比如说母亲节就定为每年的五月的第二个星期日。
现在,给你a,b,c和y1, y2(1850 ≤ y1, y2 ≤ 2050),希望你输出从公元y1年到公元y2年间的每年的a月的第b个星期c的日期。 提示:关于闰年的规则:年份是400的整数倍时是闰年,否则年份是4的倍数并且不是100的倍数时是闰年,其他年份都不是闰年。例如1900年就不是闰年,而2000年是闰年。 为了方便你推算,已知1850年1月1日是星期二。 输入格式
输入包含恰好一行,有五个整数a, b, c, y1, y2。其中c=1, 2, ……, 6, 7分别表示星期一、二、……、六、日。
输出格式
对于y1和y2之间的每一个年份,包括y1和y2,按照年份从小到大的顺序输出一行。
如果该年的a月第b个星期c确实存在,则以"yyyy/mm/dd"的格式输出,即输出四位数的年份,两位数的月份,两位数的日期,中间用斜杠“/”分隔,位数不足时前补零。 如果该年的a月第b个星期c并不存在,则输出"none"(不包含双引号)。 样例输入
5 2 7 2014 2015
样例输出
2014/05/11
2015/05/10 评测用例规模与约定
所有评测用例都满足:1 ≤ a ≤ 12,1 ≤ b ≤ 5,1 ≤ c ≤ 7,1850 ≤ y1, y2 ≤ 2050。
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int month=scanner.nextInt();
int th=scanner.nextInt();
int day=scanner.nextInt();
int start=scanner.nextInt();
int end=scanner.nextInt();
int[][] arr={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};
int year=1850;
int countyear=0;
while (year<start) {
countyear+=365+isLeap(year);
year++;
}
int days=0;
int countday;
for (int i = start; i <= end; i++) {
days=0;
for (int j = 1; j < month; j++) {
days=days+arr[isLeap(i)][j];
}
days=days+countyear;
int firstday=1+days%7;//计算该月1日的前一天为周几
countday= (th-1) * 7 + ((firstday >= day) ? (day + 7 - firstday) : (day - firstday));
if (countday>arr[isLeap(i)][month]) {
System.out.println("none");
}else {
String out=i+"/";
if (month<10) {
out=out+"0"+month+"/";
}else {
out=out+month+"/";
}
if (countday<10) {
out=out+"0"+countday;
}else {
out=out+countday;
}
System.out.println(out);
}
countyear+=365+isLeap(i);
}
}
public static int isLeap(int year) {
if ((year%4==0&&year%100!=0)||year%400==0) {
return 1;
}else {
return 0;
}
}
}
之前写的那个由于没有按照格式输出,所以只有30分。
算法的基本思想:
1、计算1850年到某年的某月第一天的天数
2、计算某月的前一天为星期几week=1+days%7;
3、计算第几个周几的日期
countday= (th-1) * 7 + ((firstday >= day) ? (day + 7 - firstday) : (day - firstday));
附计算公式。
终于得到100分了,太不容易,主要是公式的推导。