1. 程式人生 > >藍橋杯java歷年真題及答案整理41~56

藍橋杯java歷年真題及答案整理41~56

2個 sort system nds ring ram 小數 cat --

41. 低碳生活大獎賽

/*
某電視臺舉辦了低碳生活大獎賽。題目的計分規則相當奇怪:
每位選手需要回答10個問題(其編號為1到10),越後面越有難度。
答對的,當前分數翻倍;答錯了則扣掉與題號相同的分數(選手必須回答問題,不回答按錯誤處理)。
每位選手都有一個起步的分數為10分。
某獲勝選手最終得分剛好是100分,如果不讓你看比賽過程,
你能推斷出他(她)哪個題目答對了,哪個題目答錯了嗎?
如果把答對的記為1,答錯的記為0,則10個題目的回答情況可以用僅含有1和0的串來表示。
例如:0010110011 就是可能的情況。
你的任務是算出所有可能情況。每個答案占一行。
*/
package Question40_49;

public class Question41 {
    public static void exeForward(int question[],int index,int sum,int needSum) {
        if(index<=10){
            for (int i = 0; i <= 1; i++) {
                question[index]=i;
                int t=sum;
                if(i==0){
                    sum-=index;
                }else {
                    sum*=2;
                }
                exeForward(question, index+1, sum, needSum);
                question[index]=(i==1?0:1);
                sum=t;
            }
        }else {
            if(sum==needSum){
                for (int i = 1; i <= 10; i++) {
                    System.out.print(question[i]);
                }
                System.out.println();
                return;
            }else {
                return;
            }
        }

    }
    public static void main(String[] args) {
        int needSum=100;
        int question[]=new int[12];
        exeForward(question, 1, 10, 100);
    }
}

運行結果:
0010110011
0111010000
1011010000


12345678910
0010110011
0111010000
1011010000

42. 益智玩具

import java.math.BigInteger;

/*
* 漢諾塔(又稱河內塔)問題是源於印度一個古老傳說的益智玩具。
大梵天創造世界的時候做了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞著64片黃金圓盤。
大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上(可以借助第三根柱子做緩沖)。
並且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。
如圖【1.jpg】是現代“山寨”版的該玩具。64個圓盤太多了,所以減為7個,
金剛石和黃金都以木頭代替了......但道理是相同的。
據說完成大梵天的命令需要太多的移動次數,以至被認為完成之時就是世界末日!
你的任務是精確計算出到底需要移動多少次。
很明顯,如果只有2個圓盤,需要移動3次。
圓盤數為3,則需要移動7次。
那麽64個呢?
答案寫在“解答.txt”中,不要寫在這裏!
*/
package Question40_49;

import java.math.BigInteger;
import java.util.Scanner;

public class Question42MustRemember {
    public static BigInteger count=BigInteger.valueOf(0);
    public static void move(int from,int to) {
    //  System.out.println(from+"--->"+to);
        count=count.add(BigInteger.valueOf(1));
    }
    public static void hanoi(int n,int from,int to,int assist) {
        if(n>0){
            hanoi(n-1, from, assist, to);
            move(from, to);
            hanoi(n-1, assist, to, from);
        }

    }
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
    //  int n=scanner.nextInt();
        for (int i = 1; i <= 100; i++) {
            long startTime = System.currentTimeMillis();    // 程序開始時間
            hanoi(i, 1, 2, 3);
            long endTime = System.currentTimeMillis();  // 程序結束時間
            System.out.println("n="+String.format("%4d", i)+"  時,耗時"+String.format("%f", (endTime-startTime)/1000f)+"秒,  移動了"+count+" 次  ");
            count=BigInteger.valueOf(0);

        }
    }
}

43. 拼酒量

/*
有一群海盜(不多於20人),在船上比拼酒量。過程如下:打開一瓶酒,
所有在場的人平分喝下,有幾個人倒下了。再打開一瓶酒平分,又有倒下的,
再次重復...... 直到開了第4瓶酒,坐著的已經所剩無幾,海盜船長也在其中。
當第4瓶酒平分喝下後,大家都倒下了。    等船長醒來,發現海盜船擱淺了。
他在航海日誌中寫到:“......昨天,我正好喝了一瓶.......奉勸大家,開船不喝酒,喝酒別開船......”
請你根據這些信息,推斷開始有多少人,每一輪喝下來還剩多少人。
如果有多個可能的答案,請列出所有答案,每個答案占一行。
格式是:人數,人數,...
例如,有一種可能是:20,5,4,2,0
答案寫在“解答.txt”中,不要寫在這裏!
*/
package Question40_49;

public class Question43 {

    public static void main(String[] args) {
        int person[]=new int[5];
        for (person[1] = 1;  person[1]<=20 ; person[1]++) {
            for (person[2] = 1;  person[2]<person[1] ; person[2]++){
                for (person[3] = 1;  person[3]<person[2] ; person[3]++){
                    for (person[4] = 1;  person[4]<person[3] ; person[4]++){
                        if ((1.0)/person[1]+(1.0)/person[2]+(1.0)/person[3]+(1.0)/person[4]==1) {
                            for (int i = 1; i <= 4; i++) {
                                System.out.print(person[i]);
                                if(i==4){
                                    System.out.println(",0");
                                }else {
                                    System.out.print(",");
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}
運行結果:
20,5,4,2,0
18,9,3,2,0
15,10,3,2,0
12,6,4,2,0

44. 黃金分割數

import java.math.BigDecimal;

/*
* 黃金分割數0.618與美學有重要的關系。舞臺上報幕員所站的位置大約就是舞臺寬度的0.618處,
墻上的畫像一般也掛在房間高度的0.618處,甚至股票的波動據說也能找到0.618的影子....
黃金分割數是個無理數,也就是無法表示為兩個整數的比值。
0.618只是它的近似值,其真值可以通過對5開方減去1再除以2來獲得,
我們取它的一個較精確的近似值:0.618034
有趣的是,一些簡單的數列中也會包含這個無理數,這很令數學家震驚!
1 3 4 7 11 18 29 47 .... 稱為“魯卡斯隊列”。它後面的每一個項都是前邊兩項的和。
如果觀察前後兩項的比值,即:1/3,3/4,4/7,7/11,11/18 ... 會發現它越來越接近於黃金分割數!
你的任務就是計算出從哪一項開始,這個比值四舍五入後已經達到了與0.618034一致的精度。
請寫出該比值。格式是:分子/分母。比如:29/47
*/
package Question40_49;

public class Question44 {


    public static void main(String[] args) {
        int a=1,b=3,t;
        while(true){
            if(Math.abs((double)a/b-0.618034)<0.000001){
                System.out.println(a+"/"+b+" = "+(double)a/b);
                break;
            }
            t=a;
            a=b;
            b+=t;
        }
    }
}
運行結果:
1364/2207

45. 坐標

/*
*   已知平面上若幹個點的坐標。

需要求出在所有的組合中,4個點間平均距離的最小值(四舍五入,保留2位小數)。
比如有4個點:a,b,c,d,則平均距離是指:ab, ac, ad, bc, bd, cd 這6個距離的平均值。
每個點的坐標表示為:橫坐標,縱坐標
坐標的取值範圍是:1~1000
所有點的坐標記錄在in.txt中,請讀入該文件,然後計算。
註意:我們測試您的程序的時候,in.txt 可能會很大,比如包含上萬條記錄。
舉例:
如果,in.txt 內的值為:
10,10
20,20
80,50
10,20
20,10
則程序應該輸出:
11.38
*/
package Question40_49;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

public class Question45ErrorDontUnderstand {

    public static double exeForward(Vector<Point>vpoints,Vector<Point>tpoints,int index) {
//      for (Point point : tpoints) {
//          System.out.print("["+point.x+","+point.y+"]");
//      }
//      System.out.println();
        if(tpoints.size()==4){
            double t=tpoints.get(0).distance(tpoints.get(1))+tpoints.get(0).distance(tpoints.get(2))+tpoints.get(0).distance(tpoints.get(3))
                    +tpoints.get(1).distance(tpoints.get(2))+tpoints.get(1).distance(tpoints.get(3))+tpoints.get(2).distance(tpoints.get(3));
            t/=6;
            //System.out.println(t);
            return t;
        }else if (index<vpoints.size()) {
            Vector<Point>vector1=new Vector<Point>(tpoints);
            Vector<Point>vector2=new Vector<Point>(tpoints);
            vector2.add(vpoints.get(index));


            double min1=exeForward(vpoints, vector1, index+1);

            double min2=exeForward(vpoints, vector2, index+1);


            return Math.min(min1, min2);
        }

        return Double.MAX_VALUE;
    }
    public static void main(String[] args) {
        try {
            File file=new File("in.txt");
            FileInputStream fileInputStream=new FileInputStream(file);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            Vector<Point>vpoints=new Vector<Point>();
            String ts;
            while((ts=bufferedReader.readLine())!=null){
                String tss[]=ts.split("\\,");
                Point point=new Point(Integer.parseInt(tss[0]), Integer.parseInt(tss[1]));
                vpoints.add(point);
            }


            Vector<Point> tpoints=new Vector<Point>();

            System.out.println(String.format("%.2f", exeForward(vpoints, tpoints, 0)));



            bufferedReader.close();
        } catch (FileNotFoundException e) {
            // TODO: handle exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}運行結果:
11.38

46. 遞歸算法

package temp;
/**
* 遞歸算法:將數據分為兩部分,遞歸將數據從左側移右側實現全排列
*
* @param datas
* @param target
*/
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class T06 {
    // 輸出
    public static void print(List target){
        for(Object o: target){
            System.out.print(o);
        }
        System.out.println();
    }
    // 遞歸排列
    public static void sort(List datas,List target,int n){
        if(target.size()==n){
            print(target);
            return;
        }
        for(int i=0;i<datas.size();i++){
            List newDatas = new ArrayList(datas);
            List newTarget = new ArrayList(target);
            newTarget.add(newDatas.get(i));
            newDatas.remove(i);

            sort(newDatas,newTarget,n);
        }
    }
    // 主函數
    public static void main(String[] args){
        String[] s = {"a","b","c"};
        sort(Arrays.asList(s),new ArrayList(),s.length);
    }
}
運行結果:
abc
acb
bac
bca
cab
cba


方法二:
public class AllSort{
     public static void perm(String[] buf,int start,int end){       
            if(start==end){//當只要求對數組中一個字母進行全排列時,只要按該數組輸出即可
                for(int i=0;i<=end;i++){
                    System.out.print(buf[i]);
                }
                System.out.println();
            }
            else{//多個字母全排列
                for(int i=start;i<=end;i++){
                    String temp=buf[start];//交換數組第一個元素與後續的元素
                    buf[start]=buf[i];
                    buf[i]=temp;

                    perm(buf,start+1,end);//後續元素遞歸全排列

                    temp=buf[start];//將交換後的數組還原
                    buf[start]=buf[i];
                    buf[i]=temp;
                }
            }
        }
    public static void main(String[] args) {
        String buf[]={"a","b","c"};
        perm(buf,0,buf.length-1);
    }
}
運行結果:
abc
acb
bac
bca
cba
cab

47. 字符串全拜列

/*
* 字符串全拜列
*/
public class T03{
    // 輸出字符數組
    public static void print(char[] arr){
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]);
        }
        System.out.println();
    }
    // 遞歸遍歷
    public static void perm(char[] arr,int start,int end){
        if(start==end){
            print(arr); // 輸出
        }else{
            for(int i=start;i<=end;i++){
                // 換位
                char c = arr[start];
                arr[start] = arr[i];
                arr[i] = c;
                // 遞歸
                perm(arr,start+1,end);
                // 恢復數組原位
                c = arr[start];
                arr[start] = arr[i];
                arr[i] = c;
            }
        }
    }
    // 字符串轉字符數組
    public static void f(String s){
        char[] arr = s.toCharArray();
        perm(arr,0,arr.length-1);
    }
    public static void main(String[] args){
        String s = "abc";
        f(s);
    }
}
運行結果:
abc
acb
bac
bca
cba
cab

48. 親密數

/*
假設有a、b兩個數,若a的所有因子之和等於b,b的所有因子之和等於a,
並且a不等於b,則稱a和b是一對親密數。如284和220就是一對親密數。
分析:
若要找出10000以內的親密數,可使用以下算法:
(1)對每一個數i,將其因子分解出來,並將因子保存到一個數組中,再將因子之和保存到變量b1。
(2)將因子之和b1再進行因子分解,並將因子保存到一個數組中,將因子之和保存到變量b2中。
(3)若b2等於i,並且b1不等於b2,則找到一對親密數為i和b1,可將其輸出。
(4)重復步驟(1)~(3),即可找出指定範圍的親密數。
*/
package Question40_49;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;

public class Question48 {
    public static int obtain(int n) {
        int sum = 0;
        for (int i = 1; i < n; i++) {
            if (n % i == 0) {
                sum += i;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        Set<Set<Integer>> sets = new LinkedHashSet<Set<Integer>>();
        for (int i = 1; i <= n; i++) {
            int t = obtain(i);
            if (i != t) {
                if (obtain(t) == i) {
                    Set<Integer> set = new LinkedHashSet<Integer>();
                    set.add(i);
                    set.add(t);
                    sets.add(set);
                }

            }
        }
        for (Iterator iterator = sets.iterator(); iterator.hasNext();) {

            Set<Integer> set = (Set<Integer>) iterator.next();
            for (Iterator iterator2 = set.iterator(); iterator2.hasNext();) {
                Integer integer = (Integer) iterator2.next();
                System.out.print(integer);
                if (iterator2.hasNext() == false) {
                    System.out.println();
                } else {
                    System.out.print("   ");
                }

            }

        }

    }
}
運行結果:
10000
220   284
1184   1210
2620   2924
5020   5564
6232   6368

49. 標題: 世紀末的星期

    曾有邪教稱1999年12月31日是世界末日。當然該謠言已經不攻自破。

    還有人稱今後的某個世紀末的12月31日,如果是星期一則會....

    有趣的是,任何一個世紀末的年份的12月31日都不可能是星期一!! 

    於是,“謠言制造商”又修改為星期日......

    1999年的12月31日是星期五,請問:未來哪一個離我們最近的一個世紀末年(即xx99年)的12月31日正好是星期天(即星期日)?

    請回答該年份(只寫這個4位整數,不要寫12月31等多余信息)
import java.util.Scanner;


public class Question1UnAmendment {
    public static void main(String[] args) {
        int day=0;
        for (int year = 2000; ; year++) {
            day+=new Question1UnAmendment().dayOfyear(year);
            if(year%100==99&&day%7==2){
                System.out.println(year);
                break;
            }
        }
    }
    private int dayOfyear(int year) {
        if ((year%4==0&&year%100!=0)||year%400==0) {
            return 366;
        }
        else {
            return 365;
        }
    }
}

50. 標題: 馬虎的算式

    小明是個急性子,上小學的時候經常把老師寫在黑板上的題目抄錯了。

    有一次,老師出的題目是:36 x 495 = ?

    他卻給抄成了:396 x 45 = ?

    但結果卻很戲劇性,他的答案竟然是對的!!

    因為 36 * 495 = 396 * 45 = 17820

    類似這樣的巧合情況可能還有很多,比如:27 * 594 = 297 * 54

    假設 a b c d e 代表1~9不同的5個數字(註意是各不相同的數字,且不含0)

    能滿足形如: ab * cde = adb * ce 這樣的算式一共有多少種呢?


請你利用計算機的優勢尋找所有的可能,並回答不同算式的種類數。

滿足乘法交換律的算式計為不同的種類,所以答案肯定是個偶數。


答案直接通過瀏覽器提交。
註意:只提交一個表示最終統計種類數的數字,不要提交解答過程或其它多余的內容。

import java.util.Scanner;

public class Question2UnAmendment {
    public static void main(String[] args) {
        int a, b, c, d, e;
        int count=0;
        for (a = 1; a < 10; a++) {
            for (b = 1; b < 10; b++) {
                if (b != a) {
                    for (c = 1; c < 10; c++) {
                        if (c != b && c != a) {
                            for (d = 1; d < 10; d++) {
                                if (d != a && d != b && d != c) {
                                    for (e = 1; e < 10; e++) {
                                        if (e != a && e != b && e != c
                                                && e != d) {
                                            if ((a * 10 + b)
                                                    * (c * 100 + d * 10 + e) == (a
                                                    * 100 + d * 10 + b)
                                                    * (c * 10 + e)) {
                                                System.out.printf("%d%d*%d%d%d = %d%d%d*%d%d\n",a, b, c, d, e,a, d, b, c, e);
                                                count++;
                                            }
                                        }
                                    }
                                }

                            }
                        }

                    }
                }
            }
        }
        System.out.println(count);
    }
}

51. 標題: 振興中華

    小明參加了學校的趣味運動會,其中的一個項目是:跳格子。

    地上畫著一些格子,每個格子裏寫一個字,如下所示:(也可參見p1.jpg)

從我做起振
我做起振興
做起振興中
起振興中華


    比賽時,先站在左上角的寫著“從”字的格子裏,可以橫向或縱向跳到相鄰的格子裏,但不能跳到對角的格子或其它位置。一直要跳到“華”字結束。


    要求跳過的路線剛好構成“從我做起振興中華”這句話。

    請你幫助小明算一算他一共有多少種可能的跳躍路線呢?

答案是一個整數,請通過瀏覽器直接提交該數字。
註意:不要提交解答過程,或其它輔助說明類的內容。


import java.util.Scanner;

public class Question3UnAmendment {
    String indexsString[] = { "從", "我", "做", "起", "振", "興", "中", "華" };
    String s[][] = {  
{ "從", "我", "做", "起", "振" },
{ "我", "做", "起", "振", "興" },
                { "做", "起", "振", "興", "中" },
 { "起", "振", "興", "中", "華" } 
};

    private int stepForward(int i, int j, int index) {
        if (i < 4 && j < 5) {
            if (s[i][j] == indexsString[index]) {
                if (indexsString[index] == "華") {
                    return 1;
                } else {
                    return (new Question3UnAmendment()).stepForward(i + 1, j,
                            index + 1)
                            + (new Question3UnAmendment()).stepForward(i,
                                    j + 1, index + 1);
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println((new Question3UnAmendment()).stepForward(0, 0, 0));
    }
}

52. 標題:有理數類

    有理數就是可以表示為兩個整數的比值的數字。一般情況下,我們用近似的小數表示。但有些時候,不允許出現誤差,必須用兩個整數來表示一個有理數。

    這時,我們可以建立一個“有理數類”,下面的代碼初步實現了這個目標。為了簡明,它只提供了加法和乘法運算。

class Rational
{
    private long ra;
    private long rb;

    private long gcd(long a, long b){
        if(b==0) return a;
        return gcd(b,a%b);
    }
    public Rational(long a, long b){
        ra = a;
        rb = b; 
        long k = gcd(ra,rb);
        if(k>1){ //需要約分
            ra /= k;  
            rb /= k;
        }
    }
    // 加法
    public Rational add(Rational x){
        return new Rational(this.ra*x.rb+this.rb+x.ra, this.rb*x.rb);  //填空位置
    }
    // 乘法
    public Rational mul(Rational x){
        return new Rational(ra*x.ra, rb*x.rb);
    }
    public String toString(){
        if(rb==1) return "" + ra;
        return ra + "/" + rb;
    }
}

使用該類的示例:
    Rational a = new Rational(1,3);
    Rational b = new Rational(1,6);
    Rational c = a.add(b);
    System.out.println(a + "+" + b + "=" + c);


請分析代碼邏輯,並推測劃線處的代碼,通過網頁提交
註意:僅把缺少的代碼作為答案,千萬不要填寫多余的代碼、符號或說明文字!!


53. 標題:三部排序

    一般的排序有許多經典算法,如快速排序、希爾排序等。

    但實際應用時,經常會或多或少有一些特殊的要求。我們沒必要套用那些經典算法,可以根據實際情況建立更好的解法。

    比如,對一個整型數組中的數字進行分類排序:

    使得負數都靠左端,正數都靠右端,0在中部。註意問題的特點是:負數區域和正數區域內並不要求有序。可以利用這個特點通過1次線性掃描就結束戰鬥!!

    以下的程序實現了該目標。

    static void sort(int[] x)
    {
        int p = 0;
        int left = 0;
        int right = x.length-1;

        while(p<=right){
            if(x[p]<0){
                int t = x[left];
                x[left] = x[p];
                x[p] = t;
                left++;
                p++;
            }
            else if(x[p]>0){
                int t = x[right];
                x[right] = x[p];
                x[p] = t;
                right--;            
            }
            else{
                        p++       ;  //代碼填空位置
            }
        }
    }

54. 標題:錯誤票據

    某涉密單位下發了某種票據,並要在年終全部收回。

    每張票據有唯一的ID號。全年所有票據的ID號是連續的,但ID的開始數碼是隨機選定的。

    因為工作人員疏忽,在錄入ID號的時候發生了一處錯誤,造成了某個ID斷號,另外一個ID重號。

    你的任務是通過編程,找出斷號的ID和重號的ID。

    假設斷號不可能發生在最大和最小號。

要求程序首先輸入一個整數N(N<100)表示後面數據行數。
接著讀入N行數據。
每行數據長度不等,是用空格分開的若幹個(不大於100個)正整數(不大於100000)
每個整數代表一個ID號。

要求程序輸出1行,含兩個整數m n,用空格分隔。
其中,m表示斷號ID,n表示重號ID

例如:
用戶輸入:
2
5 6 8 11 9 
10 12 9

則程序輸出:
7 9


再例如:
用戶輸入:
6
164 178 108 109 180 155 141 159 104 182 179 118 137 184 115 124 125 129 168 196
172 189 127 107 112 192 103 131 133 169 158 
128 102 110 148 139 157 140 195 197
185 152 135 106 123 173 122 136 174 191 145 116 151 143 175 120 161 134 162 190
149 138 142 146 199 126 165 156 153 193 144 166 170 121 171 132 101 194 187 188
113 130 176 154 177 120 117 150 114 183 186 181 100 163 160 167 147 198 111 119

則程序輸出:
105 120


資源約定:
峰值內存消耗(含虛擬機) < 64M
CPU消耗  < 2000ms


請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多余內容。

所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
註意:不要使用package語句。不要使用jdk1.6及以上版本的特性。
註意:主類的名字必須是:Main,否則按無效代碼處理。

import java.io.IOException;
import java.util.PriorityQueue;
import java.util.Scanner;


class Question7UnAmendment{


    public static void main(String[] args) throws IOException {
        String s[]=new String[10];
        int lines;
        char ch;
        PriorityQueue<Integer>priorityQueue=new PriorityQueue<Integer>();
        lines= System.in.read()-‘0‘;
        lines++;
        int sum=0;
        while(lines>0){
            ch=(char) System.in.read();
            if(ch==‘ ‘){
                if(sum!=0){
                    priorityQueue.add(sum);
                    sum=0;
                }
            }else if(ch>=‘0‘&&ch<=‘9‘){
                if(ch==‘0‘&&sum==0){
                    priorityQueue.add(0);
                    continue;
                }
                sum*=10;
                sum+=ch-‘0‘;
            }else if(ch==‘\n‘){
                lines--;
                if(sum!=0){
                    priorityQueue.add(sum);
                    sum=0;
                }
            }
        }
        int m =-1,n = -1;
        int i=priorityQueue.peek();
        while(!priorityQueue.isEmpty()){
            if(i!=priorityQueue.peek()){
                if(priorityQueue.peek()-i==1){
                    m=i;
                    priorityQueue.add(i);
                }else if (i-priorityQueue.peek()==1) {
                    n=priorityQueue.peek();
                    priorityQueue.poll();
                }
            }
            i++;
            priorityQueue.poll();
        }
        System.out.println(m+" "+n);
    }
}

55. 標題:幸運數

    幸運數是波蘭數學家烏拉姆命名的。它采用與生成素數類似的“篩法”生成。

    首先從1開始寫出自然數1,2,3,4,5,6,....

    1 就是第一個幸運數。
    我們從2這個數開始。把所有序號能被2整除的項刪除,變為:

    1 _ 3 _ 5 _ 7 _ 9 ....

    把它們縮緊,重新記序,為:

    1 3 5 7 9 .... 。這時,3為第2個幸運數,然後把所有能被3整除的序號位置的數刪去。註意,是序號位置,不是那個數本身能否被3整除!! 刪除的應該是5,11, 17, ...

    此時7為第3個幸運數,然後再刪去序號位置能被7整除的(19,39,...) 

    最後剩下的序列類似:

    1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, ...

本題要求:

輸入兩個正整數m n, 用空格分開 (m < n < 1000*1000)
程序輸出 位於m和n之間的幸運數的個數(不包含m和n)。

例如:
用戶輸入:
1 20
程序輸出:
5

例如:
用戶輸入:
30 69
程序輸出:
8



資源約定:
峰值內存消耗(含虛擬機) < 64M
CPU消耗  < 2000ms


請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多余內容。

所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
註意:不要使用package語句。不要使用jdk1.6及以上版本的特性。
註意:主類的名字必須是:Main,否則按無效代碼處理。


import java.util.Scanner;
import java.util.Vector;




class Question8UnAmendment{


    public static void main(String[] args) {
        Vector<Integer> vector=new Vector<Integer>();
        int m,n;

        Scanner scanner=new Scanner(System.in);
        m=scanner.nextInt();
        n=scanner.nextInt();
        for(int i=0;i<=n;i++){
            vector.add(i);
        }


        //除掉序號能被2整除的
        for(int i=vector.size()-1;i>=1;i--){
            if(i%2==0){
                vector.remove(i);
            }
        }




        int index=2;
        while(index<vector.size()){
            for (int i = vector.size()-1; i>=1; i--) {
                if(i%vector.elementAt(index)==0){
                    vector.remove(i);
                }
            }
            index++;
        }



        int count=0;
        for(int i=vector.size()-1;i>=1;i--){
            if(vector.elementAt(i)==n){
                continue;
            }
            else if(vector.elementAt(i)>m){
                count++;
            }else {
                break;
            }
        }
        System.out.println(count);
    }
}

56. 標題:連號區間數

    小明這些天一直在思考這樣一個奇怪而有趣的問題:

    在1~N的某個全排列中有多少個連號區間呢?這裏所說的連號區間的定義是:

    如果區間[L, R] 裏的所有元素(即此排列的第L個到第R個元素)遞增排序後能得到一個長度為R-L+1的“連續”數列,則稱這個區間連號區間。

    當N很小的時候,小明可以很快地算出答案,但是當N變大的時候,問題就不是那麽簡單了,現在小明需要你的幫助。

輸入格式:
第一行是一個正整數N (1 <= N <= 50000), 表示全排列的規模。
第二行是N個不同的數字Pi(1 <= Pi <= N), 表示這N個數字的某一全排列。

輸出格式:
輸出一個整數,表示不同連號區間的數目。

示例:
用戶輸入:
4
3 2 4 1

程序應輸出:
7

用戶輸入:
5
3 4 2 5 1

程序應輸出:
9

解釋:
第一個用例中,有7個連號區間分別是:[1,1], [1,2], [1,3], [1,4], [2,2], [3,3], [4,4]
第二個用例中,有9個連號區間分別是:[1,1], [1,2], [1,3], [1,4], [1,5], [2,2], [3,3], [4,4], [5,5]


資源約定:
峰值內存消耗(含虛擬機) < 64M
CPU消耗  < 5000ms


請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多余內容。

所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
註意:不要使用package語句。不要使用jdk1.6及以上版本的特性。
註意:主類的名字必須是:Main,否則按無效代碼處理。
import java.util.Scanner;
import java.util.Vector;






class Question10UnAmendment{
    Vector<Integer> vectorPrimary=new Vector<Integer>();
    private boolean isContinuous(int begin,int end) {
        int max=vectorPrimary.elementAt(begin),min=vectorPrimary.elementAt(begin);
        for(int i=begin;i<=end;i++){
            if(max<vectorPrimary.elementAt(i)){
                max=vectorPrimary.elementAt(i);
                continue;
            }
            if(min>vectorPrimary.elementAt(i)){
                min=vectorPrimary.elementAt(i);
            }
        }
        if(max-min==end-begin){
            return true;
        }else {
            return false;
        }

    }
    public Vector<Integer> getVectorPrimary() {
        return vectorPrimary;
    }

    public void setVectorPrimary(Vector<Integer> vectorPrimary) {
        this.vectorPrimary = vectorPrimary;
    }


    public static void main(String[] args) {
        int N,t,count=0;
        Scanner scanner=new Scanner(System.in);
        Question10UnAmendment question10UnAmendment=new Question10UnAmendment();
        question10UnAmendment.getVectorPrimary().add(0);

        N=scanner.nextInt();
        for(int i=1;i<=N;i++){
            t=scanner.nextInt();
            question10UnAmendment.getVectorPrimary().add(t);
        }
        for(int i=1;i<question10UnAmendment.getVectorPrimary().size();i++){
            for (int j = i+1; j < question10UnAmendment.getVectorPrimary().size(); j++) {
                if(question10UnAmendment.isContinuous(i, j)){
                    count++;
                }
            }
        }
        System.out.println(count+N);


    }


}

57. 標題: 黃金連分數

    黃金分割數0.61803... 是個無理數,這個常數十分重要,在許多工程問題中會出現。有時需要把這個數字求得很精確。

    對於某些精密工程,常數的精度很重要。也許你聽說過哈勃太空望遠鏡,它首次升空後就發現了一處人工加工錯誤,對那樣一個龐然大物,其實只是鏡面加工時有比頭發絲還細許多倍的一處錯誤而已,卻使它成了“近視眼”!!


    言歸正傳,我們如何求得黃金分割數的盡可能精確的值呢?有許多方法。

    比較簡單的一種是用連分數:

                  1
    黃金數 = ---------------------
                        1
             1 + -----------------
                          1
                 1 + -------------
                            1
                     1 + ---------
                          1 + ...



    這個連分數計算的“層數”越多,它的值越接近黃金分割數。

    請你利用這一特性,求出黃金分割數的足夠精確值,要求四舍五入到小數點後100位。

    小數點後3位的值為:0.618
    小數點後4位的值為:0.6180
    小數點後5位的值為:0.61803
    小數點後7位的值為:0.6180340
   (註意尾部的0,不能忽略)

你的任務是:寫出精確到小數點後100位精度的黃金分割值。

註意:尾數的四舍五入! 尾數是0也要保留!

顯然答案是一個小數,其小數點後有100位數字,請通過瀏覽器直接提交該數字。
註意:不要提交解答過程,或其它輔助說明類的內容。


import java.math.BigInteger;

public class test5 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BigInteger one = BigInteger.ONE;
        BigInteger ten = BigInteger.TEN;
        BigInteger a = one;
        BigInteger b = one.add(one.add(one));
        BigInteger c = b;
        BigInteger sum = BigInteger.ONE;
        for(int i=0;i<300;i++){//需要精確到100位,所以循環次數要適當
            sum = a;
            for(int j=0;j<101;j++){//需要把小數點向右移動101位
            sum = ten.multiply(sum);
            }
            BigInteger res = sum.divide(c);
            c = a.add(b);
            a = b;
            b = c;
            if(res.toString().length()==101){//要判斷到101位,需要四舍五入

                System.out.println(res);

            }
        }

    }
}

58. 標題:帶分數

    100 可以表示為帶分數的形式:100 = 3 + 69258 / 714

    還可以表示為:100 = 82 + 3546 / 197

    註意特征:帶分數中,數字1~9分別出現且只出現一次(不包含0)。

    類似這樣的帶分數,100 有 11 種表示法。

題目要求:
從標準輸入讀入一個正整數N (N<1000*1000)
程序輸出該數字用數碼1~9不重復不遺漏地組成帶分數表示的全部種數。
註意:不要求輸出每個表示,只統計有多少表示法!


例如:
用戶輸入:
100
程序輸出:
11

再例如:
用戶輸入:
105
程序輸出:
6


資源約定:
峰值內存消耗(含虛擬機) < 64M
CPU消耗  < 3000ms


請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多余內容。

所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
註意:不要使用package語句。不要使用jdk1.6及以上版本的特性。
註意:主類的名字必須是:Main,否則按無效代碼處理。

import java.util.Scanner;
public class DaiFenShu
{
    static int kinds=0;
    static int a[]=new int[10];
    static boolean vis[]=new boolean[10];//全排列避免重復
    static void check(int a[],int n,int num)
    {
        int begin=String.valueOf(num).length();
        String str="";
        for(int i=1;i<n;i++) str+=a[i];
        for(int k=1;k<begin+1;k++)
        {
            int num1=Integer.valueOf(str.substring(0,k));
            if(num1<num)
            {
                for(int j=k+(n-k)/2;j<n-1;j++)
                {
                    int num2=Integer.valueOf(str.substring(k,j));
                    int num3=Integer.valueOf(str.substring(j,n-1));
                    if(num2>num3 && num2%num3==0)
                    {
                        if(num==num1+num2/num3) 
                        {    
//                            System.out.println(num+" = "+num1+"+"+num2+"/"+num3);
                            kinds++;
                        }
                    }
                }
            }
        }
    }
    static void dfs(int start,int n,int num)
    {
        if(start==n)
        {
            check(a,n,num);
        }
        else
        {
            for(int i=1;i<n;i++)
            {
                if(!vis[i])
                {
                    a[start]=i;
                    vis[i]=true;
                    dfs(start+1,n,num);
                    vis[i]=false;
                }
            }
        }
    }
    public static void main(String[] args)
    {
        Scanner cin=new Scanner(System.in);
        int num=cin.nextInt();
        long start=System.currentTimeMillis();
        dfs(1,10,num);
        long end=System.currentTimeMillis();
//        System.out.println(end-start);//運行時間
        System.out.println(kinds);    
    }
}

藍橋杯java歷年真題及答案整理41~56