POJ1002 487-3279 字符串 C语言

题目:http://poj.org/problem?id=1002

题目大意:手机键盘上字母和数字是对应的,给出几串号码,按照首位数字升序输出标准格式的有重复的号码,并输出重复次数;若无重复输出一行   思路:把输入的字符转化成7位数字,从小到大排序,找重复的数字,记录出现次数。具体看注释

提交情况:WA 3次, TLE 4次, AC 1次

总结:一直TLE,将n²的搜索改了之后变成WA,似乎还有 No duplicates. 貌似也有最后那个小句号的问题…… 之后又一次TLE , 是将字符串转换成数字的时候用了pow()。改了之后就AC了。

字符串操作各种不熟练,每次换行符什么的搞得相当纠结。这回又被同学教育了一下,要读入字符串,不要单个字符的读入,分着读容易出问题,读字符串不用考虑换行符空格之类的问题……

 

AC code :

View Code
  1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include <algorithm>
6 using namespace std;
7
8 #define MAXN (100000 + 10)
9
10 int a[7] = {1, 10, 100, 1000, 10000, 100000, 1000000}; //10的1~6次方
11
12 //char res[MAXN][15];
13
14 typedef struct TEL {
15 int num;
16 char ch[30];
17 }tels;
18 tels tel[MAXN];
19 int count[MAXN];
20 int flag;
21
22 int Change(char ch) {
23 if(ch == '0')
24 return 0;
25 if(ch == '1')
26 return 1;
27 if(ch == 'A' || ch == 'B' || ch == 'C' || ch == '2')
28 return 2;
29 if(ch == 'D' || ch == 'E' || ch == 'F' || ch == '3')
30 return 3;
31 if(ch == 'G' || ch == 'H' || ch == 'I' || ch == '4')
32 return 4;
33 if(ch == 'J' || ch == 'K' || ch == 'L' || ch == '5')
34 return 5;
35 if(ch == 'M' || ch == 'N' || ch == 'O' || ch == '6')
36 return 6;
37 if(ch == 'P' || ch == 'R' || ch == 'S' || ch == '7')
38 return 7;
39 if(ch == 'T' || ch == 'U' || ch == 'V' || ch == '8')
40 return 8;
41 if(ch == 'W' || ch == 'X' || ch == 'Y' || ch == '9')
42 return 9;
43 if(ch == '-')
44 return 99; //忽略掉,不处理
45 }
46
47 void Clear() {
48 memset(tel, 0, sizeof(tel));
49 flag = 1;
50 }
51
52 void Insert(int n) {
53 int i, j;
54 char ch = 'a';
55 int d;
56 for(i = 1; i <= n; ++i) {
57 int k = 7;
58 int t = 0;
59 for(j = 0; ; ++j){ //以后要用字符串操作,用%s效率相同,%c容易出问题
60 scanf("%c", &ch);
61 if(ch == '\n' || ch == ' ')
62 break;
63 d = Change(ch);
64 if(d >= 0 && d <= 9) {
65 tel[i].num += d * a[--k]; // pow(10, --k)会TLE , 用数组 系统函数不靠谱
66 tel[i].ch[t++] = d + '0';
67 }
68 }
69 //getchar();
70 }
71 }
72
73 void Find(int n) {
74 int i, j;
75 int cnt = 1;
76 tel[n + 1].num = -999; //最末尾加一个结束标记
77 for(i = 2; i <= n + 1; i++) { //不能用n²搜索,会TLE
78 //if(tel[i].num == -1)
79 // return;
80 if(tel[i].num != tel[i - 1].num && cnt > 1) { //排好序之后相同的数都相邻了,前后数字不一样时说明前面一组已经统计完
81 for(int j = 0; j < 3; j++) //个数大于1时按标准格式输出
82 printf("%c", tel[i - 1].ch[j]);
83 printf("-");
84 for(int k = 3; k < 7; k++)
85 printf("%c", tel[i - 1].ch[k]);
86 printf(" %d\n", cnt);
87 cnt = 1; //下一组数字,cnt置1,重新计数
88 }
89 if(tel[i].num == tel[i - 1].num) { //重复号码,计数
90 flag = 0; //标记出现重复号码
91 ++cnt;
92 }
93 }
94 if(flag) //无重复
95 printf("No duplicates.\n");
96
97 }
98
99 int cmp(tels &a, tels &b) {
100 return a.num < b.num;
101 }
102
103 int main() {
104 int n;
105 Clear();
106 scanf("%d", &n);
107 getchar(); //以后要用字符串,不要读字符
108 Insert(n);
109 sort(tel + 1, tel + n + 1, cmp);
110 Find(n);
111 //Print(n);
112 return 0;
113 }
posted @ 2011-07-24 01:26  cloehui  阅读(541)  评论(0编辑  收藏  举报