POJ 1002

POJ1002是个电话号码的问题

两种思路:

第一种:转换成整数数组,再进行排序,然后统计出现的次数。

printf("%03d-%04d %d", head, tale, count) //格式输出,刚开始时用的是%3d,一直不行,需要用%03d将空位用0补齐。 

代码如下:

方法1:524K 579MS C++
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>

#define MAX 256
int cmp(const void *a, const void *b)
{
	return *(int *)a-*(int *)b;
}

int main()
{
	int num;
	char map[26] =
	{'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','Q','7','7','8','8','8','9','9','9','Z'};
	char data[10], pstr[256];
	int i, j, k;
	scanf("%d", &num);
	int *res = (int *)malloc(num * sizeof(int));
	for(i=0;i<num;i++)
	{
		scanf("%s", pstr);
		k=0;
		for(j=0;j<strlen(pstr);j++){
			if(pstr[j]>='A'&&pstr[j]<='Z')
				data[k++] = map[pstr[j]-'A'];
			else if(pstr[j]>='0'&&pstr[j]<='9')
				data[k++] = pstr[j];
			else
				continue;
		}
		data[k] = '\0';
		res[i]=atoi(data);
	}

	qsort(res,num,sizeof(int),cmp);

	int count = 1;
	int head, tale;
	int flag = 0;
	for(i=0;i<num;i++){
		while(i<num-1 && res[i+1] == res[i]){
			count ++;
			i ++;
		}
		if(count > 1){
			head = res[i] / 10000;
			tale = res[i] % 10000;
			printf("%03d-%04d %d\n", head, tale, count);
			count = 1;
			flag = 1;
		}
	}
	if(!flag)
		printf("No duplicates.\n");
	free(res);
	return 0;
}

 

第二种:用Hash数组,需要的空间比较大。

代码如下:

39320K 657MS C++
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>

int hash[10000000];//需要的空间太大,默认情况下栈的大小不够,不能在函数里当局部变量
int main(){
	char map[26] =
{'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','Q','7','7','8','8','8','9','9','9','Z'};

	memset(hash,0,10000000);
                long num, max = 0, min = 10000000;
	int cur;
	long i, j;
	int k;
	char tel[256], tmp[256];
	scanf("%d", &num);

                for(i=0; i<num;i++){
		scanf("%s", tel);
		k = 0;
		for(j=0;j<strlen(tel);j++){
			if(tel[j]>='A'&&tel[j]<='Z')
				tmp[k++] = map[tel[j]-'A'];
			else if(tel[j]>='0'&&tel[j]<='9')
				tmp[k++] = tel[j];
			else
				continue;
		}
		tmp[k] = '\0';
		cur = atoi(tmp);
		if(cur>max) max = cur;
		if(cur<min) min = cur;
		hash[cur]++;
	}
	int flag = 0, head, tale;
	for(i=min;i<=max;i++){
		if(hash[i]>1){
			head = i / 10000;
			tale = i % 10000;
			printf("%03d-%04d %d\n",head,tale,hash[i]);
			flag = 1;
		}
	}
	if(!flag)
		printf("No duplicates.\n");

	return 0;
}

 

posted @ 2011-09-24 11:17  thomaslee  阅读(604)  评论(0编辑  收藏  举报