/*
贪心算法在于:每次都取数列中最小的两个。
为什么用链表:方便数组的插入更新,否则还需要每次更新要先找到跟新的位置,再进行数组的移动,很麻烦;
sort的运用需要掌握,如何从大到小如何从小到大
*/
#include<iostream>
#include<algorithm>
#define MAX 100
using namespace std;
bool compare(int a,int b)
{
return a>b;
}
typedef struct Link
{
int value;
Link *next;
}link,*linkp;
int main()
{
int i,j;
linkp hp,np,temp,mp;
int ans = 0;
int num;
int buf[MAX],value_t;
cin >> num;
for(i = 0;i < num;i++)
{
cin >> buf[i];
}
sort(buf,buf + num);
/*
for(i = 0;i < num;i++)
{
cout << buf[i];
}
*/
hp = np = NULL;
for(i = 0;i < num;i++)
{
if(i == 0)
{
hp = np = new link;
np->value = buf[i];
np->next = NULL;
}
else
{
np->next = new link;
np = np->next;
np->value = buf[i];
np->next = NULL;
}
}
//贪心操作
while(hp->next != NULL)
{
temp = hp->next->next;
mp = hp->next;
np = temp;
value_t = hp->value + hp->next->value;
ans += value_t;
while(np != NULL && np->value < value_t)
{
mp = np;
np = np->next;
}
//插入
mp->next = new link;
mp->next->value = value_t;
mp->next->next = np;
if(np == temp)//当第三个数大于前两个相加
{
temp = mp->next;
}
delete hp->next;
delete hp;
hp = temp;
}
cout << ans;
system("pause");
return 0;
}Huffuman树 贪心+链表
最新推荐文章于 2021-04-05 21:44:28 发布
本文介绍了一种使用链表实现贪心算法的方法,重点在于每次选取数列中最小的两个数进行操作。通过C++代码示例展示了如何构建链表,并在链表上执行贪心策略以求解特定问题。
652

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



