贪心得每次都要最小值。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
double *get_P(int *count, int len);
double *get_Time(int *length, double *p, int len);
void sort(double *array, int len);
int main(int argc, char *argv[]) {
int n,i;
scanf("%d", &n);
int *length = malloc(sizeof(int)*n);//每个程序的长度
int *count = malloc(sizeof(int)*n);//每个程序的读取频率
for (i=0; i<n; i++) {
scanf("%d %d",length+i, count+i);
}
//从频率计算概率
double *p = get_P(count, n);
//计算读取时间
double *time = get_Time(length, p, n);
//排序
sort(time, n);
double temp;
double minAverageTime = 0;
double *sum_i = malloc(sizeof(double)*n);
for (i=0; i<n; i++) {
temp += time[i];
minAverageTime += temp;
}
printf("Time: %lf\n",minAverageTime);
return 0;
}
double *get_P(int *count, int len) {
int i, sum = 0;
double *p = malloc(sizeof(double)*len);
for (i=0; i<len; i++) {
sum += count[i];//计算总频率
}
for (i=0; i<len; i++) {
p[i] = count[i]/(double)sum;//计算每个程序的概率
}
return p;
}
double *get_Time(int *length, double *p, int len) {
int i;
double *time = malloc(sizeof(double)*len);
for (i=0; i<len; i++) {
time[i] = p[i] * length[i];
}
return time;
}
void sort(double *array, int len) {
int i, j;
double temp = 0;
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}