Shoemaker's Problem
Shoemaker's Problem |
Shoemaker has N jobs (orders from customers) which he must make. Shoemaker can work on only one job in each day. For each ith job, it is known the integer Ti(1<=Ti<=1000), the time in days it takes the shoemaker to finish the job. For each day of delay before starting to work for the ith job, shoemaker must pay a fine of Si(1<=Si<=10000) cents. Your task is to help the shoemaker, writing a programm to find the sequence of jobs with minimal total fine.
The Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
First line of input contains an integer N (1<=N<=1000). The next N lines each contain two numbers: the time and fine of each task in order.
The Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
You programm should print the sequence of jobs with minimal fine. Each job should be represented by its number in input. All integers should be placed on only one output line and separated by one space. If multiple solutions are possible, print the first lexicographically.
Sample Input
1 4 3 4 1 1000 2 2 5 5
Sample Output
2 1 3 4
鞋匠在某天接了多个任务,他答应每个任务能在多少后天完成,不然要每违约一天就要交一定数量的违约金,但是他的每个任务都要花费他答应的天数。
问:他要按照什么样的顺序排序,才能使叫的违约金最小。
解析:贪心题,对于为什么用贪心策略。
我们不妨用任意相邻的两个事件a、b来说明一下。
由于a、b以外的事件是固定的,所以我们无论排成 ab 还是排成 ba ,其他部分的损失都是固定的,那么损失的差别主要来源于究竟是排成ab还是排成ba。
排ab的损失为ta*fb,排ba的损失为tb*fa,
那么如果ta*fb < tb*fa,排成ab为宜,
否则如果ta*fb > tb*fa,排成ba为宜。
这样可以得到ta/fa < tb/fb,时排ab,否则ba。
推而广之,就得到了我们的贪心策略。
注意:
每两个样例之间要输出一个空行。
t和f要用double来保存,不然相除时会不精确。
如果出现多种可能要按照字典序小的序列输出。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1005;
struct Node {
double t, fine;
int id;
}job[N];
bool cmp(Node a, Node b) {
return a.t / a.fine < b.t / b.fine;
}
int main() {
int T, n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%lf%lf",&job[i].t, &job[i].fine);
job[i].id = i;
}
sort(job+1, job+1+n,cmp);
for(int i = 1; i <= n; i++) {
printf("%d",job[i].id);
if(i != n) putchar(' ');
else putchar('\n');
}
if(T) puts("");
}
return 0;
}