iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 2
0
自我挑戰組

資工的日常系列 第 2

CPE考題 Rockabye Tobby

2017/09/26 CPE
考題連結:https://cpe.cse.nsysu.edu.tw/cpe/file/attendance/problemPdf/13190.pdf

大概題意:
題目前面講了一堆廢話/images/emoticon/emoticon05.gif
第二段開始才是重點。從醫生開的藥名和頻率,幫Tobby找出吃藥的種類和順序。

input:
第一行:要解幾組case,T(1 ≤ T ≤ 5)
每組的第一行:藥物種類量n(1 ≤ n ≤ 3∗10^3)。空白鍵後,要吃的總藥量k(1 ≤ k ≤ 10^4)
每組的第二行後:藥物名稱+"空白"+這藥物吃的頻率 同時,先出現的藥要先吃(有優先度)
output:
總共印出k(總藥量)行。格式:目前的吃到的"時間" 藥名。規則是一開始的時間都是0(但我程式碼直接給頻率),從時間最少的開始吃,時間一樣的話從優先度較高的先吃。吃完後加一次頻率,在找下一個時間最少的吃。

自己的解題程式碼

import java.util.Scanner;

public class RockabyeTobby {
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
        //讀入要解幾組Case
		int t=Integer.parseInt(scanner.nextLine());
        //一組case的for-loop
		for(int i=0;i<t;i++){
            //讀一行: 藥物種類量drugNum 要吃的總藥量drugTimes
			String[] buffer=scanner.nextLine().split(" ");
			//這裡我是讀一行在拆解 直接scanner.nextInt()讀不知道為什麼會有問題
            int drugNum=Integer.parseInt(buffer[0]);
			int drugTimes=Integer.parseInt(buffer[1]);
            //藥物的class
			DrugData[] drugData=new DrugData[drugNum];
            //把所有藥物的種類和頻率全部讀起來
			for(int j=0;j<drugNum;j++){
                //跟上面一樣,讀一行後用拆的
				String[] buffer2=scanner.nextLine().split(" ");
				String drugName=buffer2[0];
				int frequent=Integer.parseInt(buffer2[1]);
                //建立藥物資料
				drugData[j]=new DrugData(j,drugName,frequent,frequent);
			}
            //開始吃藥,總共吃 drugTimes 個
			for(int j=0;j<drugTimes;j++){
                //temp 目前最小的吃到的時間moment   一開始設為最大值  index為最小值的陣列索引值
				int temp=Integer.MAX_VALUE,index=0;
				//check最小moment
				for(int k=0;k<drugNum;k++){
					if(drugData[k].moment<temp){
                        //比較小就記綠起來
						temp=drugData[k].moment;
						index=k;
					}
				}
                //吃到藥後記綠一次,後面要加一次頻率
				drugData[index].printDrug();
				drugData[index].moment+=drugData[index].frequency;
			}
		}
		scanner.close();
	}

}
//藥物的class
class DrugData{
	int priority;//優先度,但後來發現用陣列的順序就行了,這個參數多餘了
	String name;//藥物名
	int frequency;//吃的頻率
	int moment;//目前吃到的時間
	public DrugData(int priority, String name, int frequency, int moment) {
		super();
		this.priority = priority;
		this.name = name;
		this.frequency = frequency;
		this.moment = moment;
	}
    //吃到一次藥後印出一行
	void printDrug(){
		System.out.println(this.moment+" "+this.name);
	}
}

測試資料:https://cpe.cse.nsysu.edu.tw/cpe/file/attendance/problemPdf/testData/uva13190b.php
結果:https://ithelp.ithome.com.tw/upload/images/20171221/2010786625ClOBcaK6.png
結果過長,只截最後面的畫面。

第二天終於結束了,沒想到要為程式做解說要花一個多小時= =。/images/emoticon/emoticon06.gif


上一篇
CPE考題 Digit Counting
下一篇
CPE考題 How Many Knights
系列文
資工的日常30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言