贪心
线性存储问题
如果有n段信息资料要线性存储在某种存储介质上,它们的长度分别是L1,L2,…,Ln,存储介质能够保存下所有这些信息,假设它们的使用(查询检索)的频率分别是F1,F2,…,Fn,要如何存储这些信息资料才能使平均检索时间最短。
正整数n(n<10000),信息的长度(1到10000之间)和使用的频率(万分比,在0到9000之间),总的频率之和为10000。
如何才能实现平均检索时间最短
平均检索时间最短,整体检索时间最短,所以要将检索速度最大的放在前面。因为n的值不一定,不建议定义一个很大的数组,可是使用动态存储-单链表,然后进行排序,输出。
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
typedef struct node{
int l;
int f;
int v;
int num;
struct node *next;
}it;
it *Creatlink (it ** head);
void Sort (it *head);
int main()
{
it *head;
head = (it *) malloc (sizeof (it)); /* 一定要有,否则下面的&失败 */
Creatlink (&head);
Sort (head);
return 0;
}
void Sort (it *head)
{
it *rd = head->next->next;
it *st,*s;
head->next->next = NULL;
while (rd != NULL) {
st = rd->next;
s = head;
while (s->next != NULL && rd->v <= s->next->v) {
s = s->next;
} /* 以速度v作为标准排序 */
rd->next = s->next;
s->next = rd;
rd = st;
}
rd = head->next;
while (rd != NULL) { /* 输出 */
printf("%d\n",rd->num);
rd = rd->next;
}
}
it *Creatlink (it ** head)
{
int n;
int x;
int y;
it *s,*r;
r = * head;
r->next = NULL;
scanf("%d",&n);
for (int i = 0; i < n; i++) {
s = (it *) malloc (sizeof (it));
scanf("%d %d",&x,&y);
s->l = x;
s->f = y;
s->v = x * y;
s->num = i + 1;
r->next = s;
r = s;
}
r->next = NULL;
return *head;
}