5-9 Huffman Codes (30分)

#include <iostream>
#include <queue>
#include <vector>
#include <string.h>

using namespace std;

int judge(char a[], char b[], int alen, int blen)
{
	int min = alen;
	if(blen < min)
	{
		min = blen;
	}

	int i;
	for(i = 0; i < min; i++)
	{
		if(a[i] != b[i])
		{
			return 0;
		}
	}

	return 1;
}

int main()
{
	int n;
	scanf("%d", &n);

	char ch;
	int num[70], i;
	priority_queue<int, vector<int>, greater<int>> q;

	for(i = 1; i <= n; i++)
	{
		getchar();
		scanf("%c%d", &ch, &num[i]);

		q.push(num[i]);
	}

	int a, b, ab, reswpl = 0;
	while(q.size() > 1)
	{
		a = q.top();
		q.pop();

		b = q.top();
		q.pop();

		ab = a + b;
		reswpl += ab;
		q.push(ab);
	}

	int m;
	scanf("%d", &m);

	char s[1010][70];
	int j, len[1010], curwpl, flag, k;

	for(i = 1; i <= m; i++)
	{
		curwpl = 0;
		for(j = 1; j <= n; j++)
		{
			getchar();
			scanf("%c%s", &ch, s[j]);

			len[j] = strlen(s[j]);
			curwpl += len[j] * num[j];
		}

		if(curwpl != reswpl)
		{
			printf("No\n");
			continue;
		}

		flag = 1;
		for(j = 1; j <= n; j++)
		{
			for(k = j + 1; k <= n; k++)
			{
				if(judge(s[j], s[k], len[j], len[k]) == 1)
				{
					flag = 0;
					break;
				}
			}

			if(flag == 0)
			{
				break;
			}
		}

		if(flag == 1)
		{
			printf("Yes\n");
		}
		else
		{
			printf("No\n");
		}
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:58  王景迁  阅读(1)  评论(0)    收藏  举报

导航