我一开始使用map容器,不过超时了,我也放出来!
代码如下:
01.
#include <iostream>
02.
#include <map>
03.
#include <cstdio>
04.
using
namespace
std;
05.
06.
bool
isPrime(
int
n)
07.
{
08.
if
(n < 2)
09.
return
false
;
10.
for
(
int
i = 2; i * i < n; i++)
11.
{
12.
if
(n % i == 0)
13.
return
false
;
14.
}
15.
return
true
;
16.
}
17.
int
main()
18.
{
19.
int
samples;
//测试数据组数
20.
21.
cin >> samples;
22.
cin.get();
23.
while
(samples--)
24.
{
25.
map<
char
,
int
> alpha;
26.
char
ch =
'0'
;
27.
int
i = 0;
28.
while
(ch !=
'\n'
)
29.
{
30.
ch =
getchar
();
31.
alpha[ch]++;
32.
}
33.
map<
char
,
int
>::iterator min = alpha.begin(),
34.
max = alpha.end();
35.
max--;
36.
int
r = max->second - min->second;
37.
if
(isPrime(r))
38.
cout <<
"Lucky Word"
<< endl << r << endl;
39.
else
40.
cout <<
"No Answer"
<< endl << 0 << endl;
41.
42.
43.
44.
45.
}
46.
47.
return
0;
48.
}
下面这个是AC过了的,代码如下:
01.
#include <iostream>
02.
#include <map>
03.
#include <ctime>
04.
#include <cstdio>
05.
using
namespace
std;
06.
07.
bool
isPrime(
int
n)
08.
{
09.
if
(n < 2)
10.
return
false
;
11.
for
(
int
i = 2; i <= n/2; i++)
12.
{
13.
if
(n % i == 0)
14.
return
false
;
15.
}
16.
return
true
;
17.
}
18.
int
main()
19.
{
20.
21.
int
samples;
//测试数据组数
22.
cin >> samples;
23.
while
(samples--)
24.
{
25.
// clock_t begin = clock();
26.
int
i = 0;
27.
int
alpha[26];
28.
char
str[102];
29.
scanf
(
"%s"
, str);
30.
for
(i = 0; i < 26; i++)
31.
alpha[i] = 0;
32.
for
(i = 0; str[i] !=
'\0'
; i++)
33.
{
34.
alpha[(str[i] -
'a'
)]++;
35.
}
36.
int
max = 1, min = 100;
37.
for
(i = 0; i < 26; i++)
38.
{
39.
if
(alpha[i] != 0 && max < alpha[i])
40.
max = alpha[i];
41.
if
(alpha[i] != 0 && min > alpha[i])
42.
min = alpha[i];
43.
}
44.
//cout << max << " " << min << endl;
45.
int
r = max - min;
46.
if
(isPrime(r))
47.
cout <<
"Lucky Word"
<< endl << r << endl;
48.
else
49.
cout <<
"No Answer"
<< endl << 0 << endl;
50.
// cout << "TIME:" << clock()- begin << "ms" << endl;
51.
}
52.
53.
return
0;
54.
}