算法导论代码 第16章 贪心算法

16章 贪心算法

16.1 活动选择问题

#include <stdio.h>
void recursive_activity_select(int s[], int f[], int i, int j,
			     int select_set[], int *select_num)
{
	int m = i + 1;
	while (m < j && s[m] < f[i]) {
		++m;
	}
	if (m < j) {
		select_set[(*select_num)++] = m;
		recursive_activity_select(s, f, m, j, select_set, select_num);
	}
}

void greedy_activity_select(int s[], int f[], int n, int select_set[],
			  int *select_num)
{
	int i = 1;
	select_set[(*select_num)++] = 1;
	for (int m = 2; m <= n; ++m) {
		if (s[m] >= f[i]) {
			select_set[(*select_num)++] = m;
			i = m;
		}
	}
}

int main()
{
	/*前面的0是添加的,有效数组从下标1开始*/
	int s[] = { 0, 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12 };	
	int f[] = { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
	int num=sizeof(s)/sizeof(s[0])-1;
	int select_set[num];
	int select_num = 0;
	//recursive_activity_select(s, f, 0, num+1, select_set, &select_num);
	greedy_activity_select(s,f,num,select_set,&select_num);
	printf("最大相互兼容活动子集:\n");
	for (int i = 0; i < select_num; i++) {
		printf("%d ",select_set[i]);
	}
	printf("\n");
	return 0;
}


16.3 赫夫曼编码

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
struct tree_node {
	int frequency;
	char c;
	struct tree_node *left;
	struct tree_node *right;
};
typedef struct priority_queue_type *priority_queue;
struct priority_queue_type {
	int heap_size;
	void **array;
	int (*comp) (const void *, const void *);
};
int parent(int i)
{
	return (i - 1) / 2;
}

int left_child(int i)
{
	return i * 2 + 1;
}

int right_child(int i)
{
	return i * 2 + 2;
}

void swap(void *a, void *b, size_t elem_size)
{
	if (a == NULL || b == NULL || a == b)
		return;
	char temp[elem_size];	/*变长数组 */
	memcpy(temp, a, elem_size);
	memcpy(a, b, elem_size);
	memcpy(b, temp, elem_size);
}

void heapify(priority_queue pq, int i)
{
	int left = left_child(i);
	int right = right_child(i);
	int largest = i;
	if (left < pq->heap_size
	    && pq->comp(pq->array[largest], pq->array[left]) < 0) {
		largest = left;
	}
	if (right < pq->heap_size
	    && pq->comp(pq->array[largest], pq->array[right]) < 0) {
		largest = right;
	}
	if (largest != i) {
		swap(&pq->array[i], &pq->array[largest], sizeof(void *));
		heapify(pq, largest);
	}
}

void fix_up(priority_queue pq, int i)
{
	while (i > 0 && pq->comp(pq->array[parent(i)], pq->array[i]) < 0) {
		swap(&pq->array[parent(i)], &pq->array[i], sizeof(void *));
		i = parent(i);
	}
}

priority_queue priority_queue_create(int n_length,
				     int (*comp) (const void *, const void *))
{
	priority_queue pq = malloc(sizeof(struct priority_queue_type));
	pq->array = malloc(sizeof(void *) * n_length);
	pq->heap_size = 0;
	pq->comp = comp;
	return pq;
}

void *priority_queue_top(priority_queue pq)
{
	return pq->array[0];
}

/*去掉并返回堆的第一个元素 */
void *priority_queue_extract_top(priority_queue pq)
{
	swap(&pq->array[0], &pq->array[pq->heap_size - 1], sizeof(void *));
	--pq->heap_size;
	heapify(pq, 0);
	return pq->array[pq->heap_size];
}

/*把元素key插入队列 */
void priority_queue_insert(priority_queue pq, void *key)
{
	++pq->heap_size;
	int i = pq->heap_size - 1;
	memcpy(&pq->array[i], &key, sizeof(void *));
	fix_up(pq, i);
}

bool priority_queue_is_empty(priority_queue pq)
{
	return pq->heap_size == 0;
}

void priority_queue_destroy(priority_queue pq, void (*free_key) (void *))
{
	while (!priority_queue_is_empty(pq)) {
		void *p = priority_queue_extract_top(pq);
		free_key(p);
	}
	free(pq->array);
	free(pq);
}

void tree_node_ini(struct tree_node *t, char c, int frequency)
{
	t->c = c;
	t->frequency = frequency;
	t->left = NULL;
	t->right = NULL;
}

/*最小堆的比较函数*/
int cmp_node(const void *pa, const void *pb)
{
	const struct tree_node *pleft = pa;
	const struct tree_node *pright = pb;
	return pright->frequency - pleft->frequency;
}

struct tree_node *huffman(int n, char char_array[], int frequency_array[])
{
	priority_queue pq = priority_queue_create(n, cmp_node);
	for (int i = 0; i < n; i++) {
		struct tree_node *node = malloc(sizeof(struct tree_node));
		tree_node_ini(node, char_array[i], frequency_array[i]);
		priority_queue_insert(pq, node);
	}
	for (int i = 0; i < n - 1; i++) {
		struct tree_node *z = malloc(sizeof(struct tree_node));
		tree_node_ini(z, 0, 0);
		struct tree_node *x = priority_queue_extract_top(pq);
		struct tree_node *y = priority_queue_extract_top(pq);
		z->left = x;
		z->right = y;
		z->frequency = x->frequency + y->frequency;
		priority_queue_insert(pq, z);
	}
	struct tree_node *root = priority_queue_extract_top(pq);
	priority_queue_destroy(pq, free);
	return root;
}

void create_huffman_code_table(struct tree_node *node, char *str_code, int n,
			       char huffman_code_table[][n])
{
	if (node == NULL) {
		return;
	}
	if (node->left == NULL && node->right == NULL) {
		strcpy(huffman_code_table[(int)node->c], str_code);
		return;
	}
	if (node->left != NULL) {
		char str[n];
		strcpy(str, str_code);
		strcat(str, "0");
		create_huffman_code_table(node->left, str, n,
					  huffman_code_table);
	}
	if (node->right != NULL) {
		char str[n];
		strcpy(str, str_code);
		strcat(str, "1");
		create_huffman_code_table(node->right, str, n,
					  huffman_code_table);
	}
}

void encode_huffman_code(char *str, char *result,
			 int n, char huffman_code_table[][n])
{
	strcpy(result, "");
	int len = strlen(str);
	for (int i = 0; i < len; ++i) {
		strcat(result, huffman_code_table[(int)str[i]]);
	}
}

int get_huffman_char(char *str, int i, char *result, struct tree_node *node)
{
	if (node->left == NULL && node->right == NULL) {
		int len = strlen(result);
		result[len] = node->c;
		result[len + 1] = '\0';
		return i;	//返回当前解码的位置
	}
	if (str[i] == '0')	//继续解码
	{
		return get_huffman_char(str, i + 1, result, node->left);
	} else {
		return get_huffman_char(str, i + 1, result, node->right);
	}
}

void decode_huffman_code(char *str, char *result, struct tree_node *node)
{
	int len = strlen(str);
	for (int i = 0; i < len;) {
		i = get_huffman_char(str, i, result, node);
	}
}

void tree_delete_node(struct tree_node *x, void (*free_key) (void *))
{
	if (x != NULL) {
		tree_delete_node(x->left, free_key);
		tree_delete_node(x->right, free_key);
		free(x);
	}
}

int main()
{
	char char_array[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
	int num = sizeof(char_array) / sizeof(char_array[0]);
	int frequency_array[] = { 45, 13, 12, 16, 9, 5 };
	int code_len = 10;
	char huffman_code_table[256][code_len];
	struct tree_node *root = huffman(num, char_array, frequency_array);
	create_huffman_code_table(root, "", code_len, huffman_code_table);
	for (int i = 0; i < 6; ++i) {
		printf("%c:%s\n", char_array[i],
		       huffman_code_table[(int)char_array[i]]);
	}
	char str[] = "aabe";
	char result[256] = { 0 };
	encode_huffman_code(str, result, code_len, huffman_code_table);
	printf("%s的huffman编码是:%s\n", str, result);
	strcpy(str, "");
	decode_huffman_code(result, str, root);
	printf("%s的huffman编码解码的结果是:%s\n", result, str);
	tree_delete_node(root, free);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值