30人吃飯共花費50,男的5塊,女的3塊,小孩1塊,有多少種分配方案
uj5u.com熱心網友回復:
// // 題設引數
// 總人數
int total_person = 30;
// 總錢數
int total_money = 50;
// 每個男人的消費
int per_man = 5;
// 每個女人的消費
int per_woman = 3;
// 每個孩子的消費
int per_child = 1;
// // 求解變數
// 方案數
int count = 0;
// // 中間變數
// 最大可能男人數
int max_man = total_money / per_man;
// 最大可能女人數
int max_woman;
// 最大可能孩子數
int max_child;
// 去掉男人消費后的錢數
int rem_man;
// 去掉男人和女人消費后的錢數
int rem_woman;
for (int m = max_man; m >= 0; m--) {
// System.out.println("男人:"+m);
rem_man = total_money - m * per_man;
max_woman = rem_man / per_woman;
for (int w = max_woman; w >= 0; w--) {
// System.out.println("\t女人:"+w);
rem_woman = rem_man - w * per_woman;
max_child = rem_woman / per_child;
// System.out.println("\t\t小孩:"+max_child);
if (m + w + max_child == total_person && rem_woman - max_child * per_child == 0) {
count++;
System.out.println("方案【" + count + "】男人:" + m + ", 女人:" + w + ", 小孩:" + max_child);
}
}
}
System.out.println("方案數:" + count);
uj5u.com熱心網友回復:
可以理解為n*1 + m*2 + k*5 = 50, n + m + k = 30的解,暴力遍歷就可以了int solutions = 0;
for (int child = 0; child <= 30; child++) {
for (int women = 0; women <= 30 - child; women++) {
int man = 30 - child - women;
if (child + women * 2 + man * 5 == 50) {
solutions++;
}
}
}
System.out.println(solutions);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/154629.html
標籤:Eclipse
