鞋匠的烦恼

(Shoemaker's Problem)

A shoemaker has N orders from customers which he must satisfy. The shoemaker can work on only one job in each day, and jobs usually take several days. For the ith job, the integer Ti ( 1$ \le$Ti$ \le$1, 000) denotes the number of days it takes the shoemaker to finish the job.

But popularity has its price. For each day of delay before starting to work on the ith job, the shoemaker has agreed to pay a fine of Si ( 1$ \le$Si$ \le$10, 000) cents per day. Help the shoemaker by writing a program to find the sequence of jobs with minimum total fine.

Input

The input begins with a single positive integer on a line by itself indicating the number of the test cases, followed by a blank line. There is also a blank line between two consecutive cases.

The first line of each case contains an integer reporting the number of jobs N, where 1$ \le$N$ \le$1, 000. The ith subsequent line contains the completion time Ti and daily penalty Si for the ith job.

 Output

For each test case, your program should print the sequence of jobs with minimal fine. Each job should be represented by its position in the input. All integers should be placed on only one output line and each pair separated by one space. If multiple solutions are possible, print the first one in lexicographic order.

The output of two consecutive cases must be separated by a blank line.

 Sample  Input

1

4
3 4
1 1000
2 2
5 5

 Sample Output 

2 1 3 4

 

 

 

解答:

假设已经有一个排序结果,则考察相邻两个订单,A和B,将A和B交换,因为交换操作不会影响A,B之前和之后的订单的罚金,所以如果A和B交换后,罚金变少,则交换,否则不交换。

可以知道,如果存在相邻两个订单应该被交换,则一定不是最优排序。因此,使用类似于冒泡排序的算法,检查相邻订单,使罚金更小。

 

代码:

 

#include <stdio.h>
#include <stdlib.h>

struct order {
  int t;
  int s;
  int id;
};

int main(){

  int test=0,n=0,i=0,j=0;
  struct order tmp;
  struct order* a;
  
  scanf("%d", &test);
  
  while(test--){
    scanf("%d", &n);
    a = (struct order*)malloc(sizeof(struct order)*n);
    for(i=0;i<n;i++){
      scanf("%d %d", &(a[i].t), &(a[i].s) );
      a[i].id = i+1;
    }


    for(i=0;i<n-1;i++){
      for(j=0; j<n-i-1; j++){
        if( a[j+1].t*a[j].s < a[j].t*a[j+1].s  || ( a[j+1].t*a[j].s == a[j].t*a[j+1].s && a[j+1].id < a[j].id) ){
           tmp = a[j];
          a[j] = a[j+1];
          a[j+1] = tmp;
        } 
      }
    }

    for(i=0;i<n-1;i++){
      printf("%d ", a[i].id);
    }
    printf("%d\n",a[n-1].id);
    if(test != 0)
        printf("\n");
    free(a);
  }
  
  return 0;
}

 

Submit url = http://www.programming-challenges.com/pg.php?page=downloadproblem&probid=110405&format=html

 

原文地址:https://www.cnblogs.com/apprentice89/p/2830177.html