洛谷-P1223 排队接水-java解题方法

P1223 排队接水

题目描述

有 n个人在一个水龙头前排队接水,假如每个人接水的时间为 T_i,请编程找出这 n个人排队的一种顺序,使得 n个人的平均等待时间最小。

输入格式

第一行为一个整数 n。

第二行 n个整数,第 i个整数 T_i 表示第 i个人的等待时间 T_i。

输出格式

输出文件有两行,第一行为一种平均时间最短的排队顺序;第二行为这种排列方案下的平均等待时间(输出结果精确到小数点后两位)。

题解

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = Integer.parseInt(scan.nextLine());
		String[] str= scan.nextLine().split(" "); 
		scan.close();
		List<N> list = new ArrayList<>();
		double arg = 0.0;
		for(int i=0;i<str.length;i++) {
			list.add(new N(i+1,Integer.parseInt(str[i])));
		}
		Collections.sort(list);
		for(int i=0;i<list.size();i++) {
			System.out.print(list.get(i).id+" ");
			if(i!=list.size()-1)
				arg+=list.get(i).time*(n-i-1);
		}
		System.out.println();
		System.out.printf("%.2f",arg/n);
	}
}
class N implements Comparable<N>{
	public int id;
	public int time;
	public N(int id,int time) {
		this.id=id;
		this.time=time;
	}
	@Override
	public int compareTo(N o) {
		if(this.time>=o.time) {
			return 1;
		}else {
			return -1;
		}
	}
	@Override
	public String toString() {
		return "N [id=" + id + ", time=" + time + "]";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜柠函

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值