Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Java 优先队列

Posted by Dennisguo at 2019-03-19 13:04:05 on Problem 3253
import java.util.PriorityQueue;
import java.util.Scanner;

public class FenceRepair {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while(in.hasNext()){
            long cost = 0; //总代价
            PriorityQueue queue = new PriorityQueue(); //存放木板的长度 注意不能识别泛型

            int N =in.nextInt();
            for (int i = 0; i < N; i++) {
                //入队N块木板
                queue.offer(in.nextInt());
            }
            while (queue.size() > 1){ //只要队列中的元素大于1 就仍然需要合并
                int firstMin = ((Integer)queue.poll()).intValue();  //第一小
                int secondMin = ((Integer)queue.poll()).intValue();  //第二小
//没有自动拆箱 只能手动转换类型
                int temp = firstMin+ secondMin;  //合并两块最小的木板
                cost += temp;
                queue.add(temp);  //合并后的木板从新入队
            }
            System.out.println(cost);

        }
    }

}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator