Surprising Strings
Time Limit: 1000 MS Memory Limit: 65536 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
[Submit] [Status] [Discuss]
Description
The D-pairs of a string of letters are the ordered pairs of letters that are distance D from each other. A string is D-unique if all of its D-pairs are different. A string is surprising if it is D-unique for every possible distance D.
Consider the string ZGBG. Its 0-pairs are ZG, GB, and BG. Since these three pairs are all different, ZGBG is 0-unique. Similarly, the 1-pairs of ZGBG are ZB and GG, and since these two pairs are different, ZGBG is 1-unique. Finally, the only 2-pair of ZGBG is ZG, so ZGBG is 2-unique. Thus ZGBG is surprising. (Note that the fact that ZG is both a 0-pair and a 2-pair of ZGBG is irrelevant, because 0 and 2 are different distances.)
Acknowledgement: This problem is inspired by the “Puzzling Adventures” column in the December 2003 issue of Scientific American.
Input
The input consists of one or more nonempty strings of at most 79 uppercase letters, each string on a line by itself, followed by a line containing only an asterisk that signals the end of the input.
Output
For each string of letters, output whether or not it is surprising using the exact output format shown below.
Sample Input
ZGBG
X
EE
AAB
AABA
AABB
BCBABCC
*
Sample Output
ZGBG is surprising.
X is surprising.
EE is surprising.
AAB is surprising.
AABA is surprising.
AABB is NOT surprising.
BCBABCC is NOT surprising.
Source
Mid-Central USA 2006
题目解释:如果输入的字符串为ZGBG
则第一个字符串可以拆分为
K = 0时,ZG、GB、BG; 每一个均不相同
K = 1时,ZB、GG;每一个也均不相同
K = 2时,ZG 只有一个不需要判断,所以输入的该子串是一个SurprisingString
思路:中级水题,利用STL中的map标记
#include <iostream>
#include <string.h>
#include <map>
using namespace std;
int main()
{
char s[80];
while(cin >>s && s[0] != '*')
{
/*长度小于2的一定是supring字符串*/
int len = strlen(s);
if(len <= 2)
{
cout << s << " is surprising." <<endl;
continue;
}
else
{
bool mark = true;
for(int d = 0; d<len -2; d++) //d的取值范围是0~len - 2;
//所构建的子串长度为该字符串的长度-2因为不包含该子串的后三位同时出现的情况
{
map<string,bool>flag; //创建map序列对应关系
bool sign = true; //标记新建的序列是否是一个suringstring子串
for(int i = 0; i<= len - d - 2; i++)
{
char pari[3] = {s[i],s[i+d+1],'\0'}; //构建字符对
if(!flag[pari])
{
flag[pari] = true;
}
else
{
sign = false;
break;
}
}
if(!sign)
{
mark=false; //存在非D-unique,s不是Surprising String
break;
}
}
if(mark)
cout << s << " is surprising." << endl;
else
cout << s << " is not surprising."<<endl;
}
}
return 0;
}