POJ 2974 487-3279 解题报告
POJ 2974 487-3279 解题报告
编号:2974
考查点:字符串处理、排序,要善于利用系统库函数.
思路:自己思考的方法和书上一致,前面的字符串处理也搞定了,排序太麻烦,看书后用系统函数qsort()加函数指针compare()轻松搞定
提交情况:最后那个输出字符串忘了加 . 导致WA一次,汗..
Source Code:
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char ch[100000][9];
int compare(const void* elem1,const void* elem2)
{
return strcmp((char*)elem1,(char*)elem2);
}
void decode(char* pch)
{
static int count = 0;
int i = 0;
while (*pch)
{
if (*pch=='-')
{
*pch++;
continue;
}
if (i==3)
{
i++;
}
if (*pch>='0'&&*pch<='9')
{
ch[count][i++] = *pch;
}
else
{
switch (*pch)
{
case 'A':
case 'B':
case 'C':
ch[count][i++] = '2';break;
case 'D':
case 'E':
case 'F':
ch[count][i++] = '3';break;
case 'G':
case 'H':
case 'I':
ch[count][i++] = '4';break;
case 'J':
case 'K':
case 'L':
ch[count][i++] = '5';break;
case 'M':
case 'N':
case 'O':
ch[count][i++] = '6';break;
case 'P':
case 'R':
case 'S':
ch[count][i++] = '7';break;
case 'T':
case 'U':
case 'V':
ch[count][i++] = '8';break;
case 'W':
case 'X':
case 'Y':
ch[count][i++] = '9';break;
default:
cout<<"Error"<<endl;break;
}
}
pch++;
}
ch[count++][3] = '-';
}
int main()
{
memset(ch,0,100000*9*sizeof(char));
int n;
cin>>n;
for (int i=0;i<n;i++)
{
char str[16];
cin>>str;
decode(str);
}
qsort(ch,n,9,compare);//included in stdlib.h
int i,j;
i = j =0;
bool flag = true;
while (i<n)
{
j = i;
i++;
while (i<n&&strcmp(ch[i],ch[j])==0)
{
i++;
}
if (i-j>1)
{
cout<<ch[j]<<" "<<i-j<<endl;
flag = false;
}
}
if (flag)
{
cout<<"No duplicates."<<endl;
}
return 0;
}
#include <string.h>
#include <stdlib.h>
using namespace std;
char ch[100000][9];
int compare(const void* elem1,const void* elem2)
{
return strcmp((char*)elem1,(char*)elem2);
}
void decode(char* pch)
{
static int count = 0;
int i = 0;
while (*pch)
{
if (*pch=='-')
{
*pch++;
continue;
}
if (i==3)
{
i++;
}
if (*pch>='0'&&*pch<='9')
{
ch[count][i++] = *pch;
}
else
{
switch (*pch)
{
case 'A':
case 'B':
case 'C':
ch[count][i++] = '2';break;
case 'D':
case 'E':
case 'F':
ch[count][i++] = '3';break;
case 'G':
case 'H':
case 'I':
ch[count][i++] = '4';break;
case 'J':
case 'K':
case 'L':
ch[count][i++] = '5';break;
case 'M':
case 'N':
case 'O':
ch[count][i++] = '6';break;
case 'P':
case 'R':
case 'S':
ch[count][i++] = '7';break;
case 'T':
case 'U':
case 'V':
ch[count][i++] = '8';break;
case 'W':
case 'X':
case 'Y':
ch[count][i++] = '9';break;
default:
cout<<"Error"<<endl;break;
}
}
pch++;
}
ch[count++][3] = '-';
}
int main()
{
memset(ch,0,100000*9*sizeof(char));
int n;
cin>>n;
for (int i=0;i<n;i++)
{
char str[16];
cin>>str;
decode(str);
}
qsort(ch,n,9,compare);//included in stdlib.h
int i,j;
i = j =0;
bool flag = true;
while (i<n)
{
j = i;
i++;
while (i<n&&strcmp(ch[i],ch[j])==0)
{
i++;
}
if (i-j>1)
{
cout<<ch[j]<<" "<<i-j<<endl;
flag = false;
}
}
if (flag)
{
cout<<"No duplicates."<<endl;
}
return 0;
}
总结:书上给了一种字符索引到数字的方法,char map[] = “2223334445556667777888999”,这个确实比switch/case好太多.. 以后要用熟练stdlib.h和string.h里的函数。
By Ns517
Time