java--解決噴水裝置問題(兩種方法)

來源:互聯網
上載者:User
描述 現有一塊草坪,長為20米,寬為2米,要在橫中心線上放置半徑為Ri的噴水裝置,每個噴水裝置的效果都會讓以它為中心的半徑為實數Ri(0<Ri<15)的圓被濕潤,這有充足的噴水裝置i(1<i<600)個,並且一定能把草坪全部濕潤,你要做的是:選擇盡量少的噴水裝置,把整個草坪的全部濕潤。 輸入 第一行m表示有m組測試資料
每一組測試資料的第一行有一個整數數n,n表示共有n個噴水裝置,隨後的一行,有n個實數ri,ri表示該噴水裝置能覆蓋的圓的半徑。 輸出 輸出所用裝置的個數 範例輸入
252 3.2 4 4.5 6 101 2 3 1 2 1.2 3 1.1 1 2

範例輸出

25

方法一:(數組方法)

import java.util.Arrays;import java.util.Scanner;public class Main2 {private final static double width = 20;public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n= sc.nextInt();//n=2while(n-- > 0){//輸入有幾個噴水裝置int num = sc.nextInt();//num=5Double[] rArray = new Double[num];//接收一個字串,變成一個字串數組for(int i=0;i<num;i++){rArray[i] = sc.nextDouble();}Arrays.sort(rArray);//將數組中的資料按照升序排序2 3.2 4 4.5 6double dWidth = 0;//3  3  2  2  2  1.2  1.1  1  1  1for(int j=rArray.length-1;j>0;j--){//取出該數組中的最大值dWidth = dWidth + 2*Math.sqrt(rArray[j]*rArray[j]-1);if(dWidth > width){//說明System.out.println(rArray.length-j);//說明找到了盡量少的噴水裝置break;}}}}}

方法二:

運用集合

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();// n=2while (n-- > 0) {// 共有幾個噴水裝置int num = sc.nextInt();// 5個List<Double> list = new ArrayList<Double>();// 通過控制台輸入2 3.2 4 4.5 6 ,然後存入到list中for (int i = 0; i < num; i++) {list.add(sc.nextDouble());}// 將list輸入中的資料按照從大到小的順序Collections.sort(list, new Comparator<Double>() {@Overridepublic int compare(Double o1, Double o2) {return o2.compareTo(o1);}});// 6 4.5 4 3.2 2double width = 20;// 定義矩形的長20米int count = 0;// 定義所用裝置的個數,預設是0個while (width > 0) {// 取出第一個數Double r = list.get(0);// 6width = width - 2 * Math.sqrt(r * r - 1);count++;// 讓用到的噴水裝置自增// 然後刪除這個list集合中的最大的數list.remove(0);}System.out.println(count);}}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.