这道题的关键就是
1.闰年
2. 3月n日,是 1月+2月+n
- import java.util.*;
- public class Main {
- public static void main(String[] args){
- Scanner in = new Scanner(System.in);
- int y = in.nextInt();
- int m = in.nextInt();
- int d = in.nextInt();
- int[] day = {31,59,90,120,151,181,212,243,273,304,334,365};
- int sum = 0;
-
- if(m >= 2){
- sum = sum + day[m-2];
-
- }
- sum += d;
- if(m > 2){//如果是m是二月份就没必要进来到里面+1了
- if(y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)){
- sum +=1;
- }
- }
-
- System.out.println(sum);
- }
- }
思路:定义一个按月份相加的天数数组,如果输入的月份为1月,那么就没必要加上月份,直接加day就行了,如果输入的月份大于等于2,那么就要完整的加上前面月份的天数,接着再加上该月的天数
如果是闰年,同样的,如果输入的月份小于或者等于2的话就没必要+1了,虽然这是给闰年准备的,但是2月3 == 1月 + 3
所以哪怕是润年,也要根据输入的月份来判断是否能加上2月这一天
上面这段代码难想
普通写法(苦逼写法)
- import java.util.*;
-
- public class Main{
- public static void main(String[] args){
- Scanner in = new Scanner(System.in);
- int year = in.nextInt();
- int month = in.nextInt();
- int day = in.nextInt();
-
- // //判断合法日期
- // if(!dayNice(year,month,day)){
- // return;
- // }
-
- //平年数组
- int[] arrDay = {31,28,31,30,31,30,31,31,30,31,30,31};
- if(isRun(year)){
- arrDay[1] = 29;
- }
-
- int sumDay = 0;
- for(int i = 0; i < month-1; i++){
- sumDay += arrDay[i];
- }
- System.out.println(sumDay+day);
-
- }
-
- //判断平年闰年
- public static boolean isRun(int year){
- if((year%4 == 0 && year % 100 != 0) || year % 400 == 0){
- return true;
- }
- return false;
- }
-
- // //判断输入是否合法
- // public static boolean dayNice(int year, int month, int day){
- // if(year >= 1000 && (month > 0 && month <13) && (day > 0 && day <= 31)){
- // if(isRun(year) && month==2 && day>29){
- // return false;
- // }else if(month == 2 && day>28){
- // return false;
- // }
- // return true;
- // }
- // return false;
- // }
-
- }
楼主写的时候甚至判断了输入的日期是否合法!!!!!!!!!纯纯大冤种
思路:
1先把球放在数组里,并排序
2.从第一个球开始往下递归,先是a0和a1如果a0+a1>a0*a1,就继续往下递归,a0+a1+a2>a0*a1*a2,接着递归到a3,发现sum < mutil ,就要回溯
3,此时sum+a3,mutil * a3, 所以回溯就是把sum-a3,mutil/3 回到上一步,那接下来就没必要再去尝试a4了,因为a3不成立,加上这个数组是有序的,接着往下是没有意义的
4.回溯到上一层后,a0+a1+a3,因为+a2是成立的,但已经回溯回来了,就往下一个元素去尝试了
5.有一个特殊情况,就是如果a0=1,此时的sum=mutil,但1和任何数的和都大于1和任何数的积
所以此时不需要回溯,仍然要继续往下递归
- import java.util.*;
- public class Main {
- public static void main(String[] args){
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- int[] a = new int[n];
- for(int i = 0; i < n; i++){
- a[i] = in.nextInt();
- }
- Arrays.sort(a);//排序
- System.out.println(count(a,n,0,0,1));
- }
-
- public static int count(int[] a, int n, int pos, int sum, int mutil){
- int count = 0;
- for(int i = pos; i < n; i++){
- sum = sum + a[i];
- mutil = mutil * a[i];
- if(sum > mutil){
- count = count + 1 + count(a,n,i+1,sum,mutil);
- }else if(a[i] == 1){
- //这里主要是用来把控,a[0] == 1 的情况
- count = count + count(a,n,i+1,sum,mutil);
- }else{
- break;
- }
- //到这里是被break出来的,要回溯
- sum = sum - a[i];
- mutil = mutil / a[i];
- //如果此刻的值和下一个值相等,就直接跳过下一个值
- while(i < n-1 && a[i] == a[i+1]){
- //要用while,不是if
- i++;
- }
- }
- return count;
- }
-
- }
如果回溯回来后,发现下一个值跟当前值一样,就要跳过当前值,i++,不然继续递归相同值是没有意义的