整理音乐
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
请用链表完成下面题目要求。
xiaobai 很喜欢音乐,几年来一直在收集好听的专辑。他有个习惯,每次在听完一首音乐后会给这首音乐打分,而且会隔一段时间给打好分的音乐排一个名次。今天 xiaobai 打开自己的音乐文件夹,发现有很多不同时期打过分的排好序的子音乐文件夹,他想把这些音乐放到一块,组成一个分数有序的序列。由于音乐文件很多,而文件里音乐的数目也是不确定的,怎么帮帮 xiaobai 完成这件工作呢?
Input
输入数据第一行为一个整数n(n<1000),代表文件夹的数量。接下来是n个文件夹的信息,每个文件夹信息的第一行是一个数字m(m<=10000),代表这个文件夹里有m首歌,后面m行每行一个歌曲名、分数,之间用空格分开。歌曲名称不超过5个字符。
Output
输出一行,为所有音乐组成的一个序列,音乐只输出名字。
如果音乐分数相同则按照音乐名字典序进行排序。
Sample Input
3
4
aaa 60
aab 50
aac 40
aad 30
2
kkk 60
kkd 59
3
qow 70
qwe 60
qqw 20
Sample Output
qow aaa kkk qwe kkd aab aac aad qqw
Hint
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char name[6];
int num;
struct node*next;
};
struct node*create(int n)
{
struct node*head,*tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
int i;
for(i=1; i<=n; i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%s %d",p->name,&p->num);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
struct node*merge(struct node*head1,struct node*head2)
{
struct node*p1,*p2,*tail;
p1=head1->next;
p2=head2->next;
tail=head1;
free(head2);
while(p1&&p2)
{
if(p1->num>p2->num)
{
tail->next=p1;
tail=p1;
p1=p1->next;
}
else if(p1->num<p2->num)
{
tail->next=p2;
tail=p2;
p2=p2->next;
}
else
{
if(strcmp(p1->name,p2->name)<0)
{
tail->next=p1;
tail=p1;
p1=p1->next;
}
else if(strcmp(p1->name,p2->name)>0)
{
tail->next=p2;
tail=p2;
p2=p2->next;
}
}
}
if(p1)
{
tail->next=p1;
}
else
{
tail->next=p2;
}
return head1;
}//这个就是链表的排序之后合并
int main()
{
int n,m;
scanf("%d %d",&m,&n);
struct node*head1,*head2,*p;
scanf("%d",&n);
head1=create(n);
int i;
for(i=2; i<=m; i++)
{
scanf("%d",&n);
head2=create(n);
head1=merge(head1,head2);//之前先建立一个链表,然后在输入,比较1和2,然后更新1,输入新的2,再进行比较
}
p=head1->next;
while(p)
{
if(p==head1->next)
{
printf("%s",p->name);
}
else
{
printf(" %s",p->name);
}
p=p->next;
}
printf("\n");
return 0;
}
思路:这个的思路关键在怎么把有序的各个部分连接起来,就相当于两个链表的合并,合并完之后又是一个新的有序的长链表,之后再和新输入的链表进行比较,确定谁在前谁在后又连接成了新的长链表,之后再输入一个链表,又比较,就有重复前面的过程
该问题描述了如何利用链表数据结构将多个按分数排序的音乐文件夹合并成一个整体有序序列。输入包含多个文件夹,每个文件夹有自己的歌曲和评分。输出要求按照分数从高到低排列,相同分数的歌曲按名字排序。解决方法涉及链表的合并和排序操作。
2059

被折叠的 条评论
为什么被折叠?



