问题
【问题描述】
有n个某种商品供应商,某地有m个商店,商店需要从供应商那里进货该商品,每个供应商的供应能力有上限,每个商店都有自己的商品需求量(need[i]:表示第i个商店的需求),每个供应商运送单位商品到商店需要一个运费。
【输入形式】
输入说明:第一行包含两个整数N,M
接下来N行包含三个整数,第一个数表示供应商编号,第二数表示供应能力上限,表示该供应商的供应量不能超过这个上限,第三个数表示运送单位商品到商店的运费。
接下来M行包含两个整数,第一个数表示商店编号,第二个数表示某种商品的需求量。
【输出形式】
输出说明:若可以满足所有商店需求,则输出格式如下:每行第一个数表示供应商编号,第二个数为商店编号,第三个数为供应量。
如:1 2 20
表示第1个供应商给第2个商店供应20个单位量的商品
按商店编号顺序,输出所有供应路径(最后一行无换行符)。
若不满足,输出-1
【样例输入】
4 4
0 20 8
1 15 3
2 55 6
3 40 10
0 28
1 36
2 49
3 12
【样例输出】
1 0 15
2 0 13
2 1 36
2 2 6
0 2 20
3 2 23
3 3 12
思路
本道题主要就是一个排序和一个简单的贪心,可以类比找最少零钱数问题
代码
//package homework.three;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class SupplierProblem {
public static void main(String[]args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Supplier>suppliers = new ArrayList<>();
ArrayList<Shop>shops = new ArrayList<>();
int num = 0;int limit = 0; int fee = 0;
int sum1 = 0;
for(int i = 0 ; i < n ; i ++){
num = scanner.nextInt();
limit = scanner.nextInt();
fee = scanner.nextInt();
suppliers.add(new Supplier(num,limit,fee));
sum1 += limit;
}
int need = 0; int sum2 = 0;
for(int i = 0 ; i < m ;i ++){
num = scanner.nextInt();
need = scanner.nextInt();
shops.add(new Shop(num,need));
sum2 += need;
}
Collections.sort(suppliers, new Comparator<Supplier>() {
@Override
public int compare(Supplier o1, Supplier o2) {
return o1.fee - o2.fee;
}
});
// System.out.println("sorted data");
// for(Supplier e: suppliers){
// System.out.println(e.num + " " + e.upperLimit + " " + e.fee);
// }
if(sum1 < sum2){
System.out.println(-1);
return;
}
int j = 0;
for(int i = 0 ; i < m ; i ++){
while(shops.get(i).need > 0){
if(suppliers.get(j).upperLimit >= shops.get(i).need){
suppliers.get(j).upperLimit -= shops.get(i).need;
System.out.println(suppliers.get(j).num + " " + shops.get(i).num + " " + shops.get(i).need);
shops.get(i).need = 0;
}else{
shops.get(i).need -= suppliers.get(j).upperLimit;
System.out.println(suppliers.get(j).num + " " + shops.get(i).num + " " + suppliers.get(j).upperLimit);
suppliers.get(j).upperLimit = 0;
j++;
}
}
}
}
}
class Supplier{
int num;
int upperLimit;
int fee;
Supplier(int num,int u,int f){
this.fee = f;
this.upperLimit = u;
this.num = num;
}
}
class Shop{
int num;
int need;
Shop(int _num, int _need){
this.need = _need;
this.num = _num;
}
}