HDOJ-ACM1005(JAVA)

转载声明:原文转自http://www.cnblogs.com/xiezie/p/5502918.html

 

JAVA语言实现:

拿到题目第一反应是简单地实现递归:

import java.util.*;

import java.io.*;

public class Main{

    public static void main(String[] arg){
        Main m = new Main();
        Scanner scan = new Scanner(new BufferedInputStream(System.in));
        while(scan.hasNextInt()){
            int a = scan.nextInt();
            int b = scan.nextInt();
            int n = scan.nextInt();
            if(a==0&&b==0&&n==0){
                break;
            }
            int result = m.f(a,b,n);
            System.out.println(result);
        }
        scan.close();
    }
    
    public int f(int a, int b ,int n){
        int result = 0;
        if(n>2){
            result = (a*f(a,b,n-1) + b*f(a,b,n-2))%7;
        }else{
            result = 1;
        }
        return result;
    }
}

在实现时 还是考虑到JVM能够递归的深度,所以报出Memory Limit Exceeded的错误   让我觉得很正常,而且实现上不优雅~

 

第二次是将递归改为循环  自我感觉良好  结果  报了Time Limit Exceeded的错误

一下让我措手不及~

import java.util.*;

import java.io.*;

public class Main{

    public static void main(String[] arg){
        Scanner scan = new Scanner(new BufferedInputStream(System.in));
        while(scan.hasNextInt()){
            int a = scan.nextInt();
            int b = scan.nextInt();
            int n = scan.nextInt();
            if(a==0&&b==0&&n==0){
                break;
            }
            int result = 1;
            int result1 = 1,result2;
            if(n>2){
                int m = n+1;
                for(int i = 3 ; i != m ; i ++ ){
                    result2 = result1;
                    result1 = result;
                    result = (a*result1 + b * result2 )%7;
                }
            }
            System.out.println(result);
        }
        scan.close();
    }

 

最后还是得分析算法 - -

这个f(n)得出的数字 都在0-6,网上的说法是 A%7,B%7 所以49个数字一个周期

这个有考虑过  但是实现时 还是没去考虑这个 - -  还是太懒~

于是  代码实现上是

import java.util.*;

import java.io.*;

public class Main{

    public static void main(String[] arg){
        Scanner scan = new Scanner(new BufferedInputStream(System.in));
        while(scan.hasNextInt()){
            int a = scan.nextInt();
            int b = scan.nextInt();
            int n = scan.nextInt();
            if(a==0&&b==0&&n==0){
                break;
            }
            int result = 1;
            int result1 = 1,result2;
            int i = 3;
            int m = n%49 + 1;
            if(m!=1&&m!=2){
                
                while(i++<m){
                    result2 = result1;
                    result1 = result;
                    result = (a*result1 + b * result2 )%7;
                }
            }
            System.out.println(result);
        }
        scan.close();
    }
}

  

posted on 2016-05-17 19:49  xiezie  阅读(265)  评论(0编辑  收藏  举报

导航