//600K 0MS G++
#include <set>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
struct classcomp {
bool operator() (const char* lhs, const char* rhs) const {
// if (lhs[0] == rhs[0] && lhs[1] == rhs[1]) {
// return 0;
// } else {
// return 1;
// }
return lhs[0] == rhs[0] ? lhs[1] > rhs[1] : lhs[0] > rhs[0];
}
};
typedef set<const char*, classcomp> Dset;
Dset dset;
typedef set<const char*, classcomp>::iterator DsetIt;
set<const char*, classcomp>::iterator it;
char checkSurprising(const string str) {
if (str.length() <=2) {
return 1;
} else {
for (int D = 1; D < str.length() - 1; D++) {
for (DsetIt curIt = dset.begin(); curIt != dset.end(); curIt++) {
delete [] (*curIt);
}
dset.clear();
// printf("BEGIN\n");
for (int i = 0; i <= str.length() - D -1; i++) {
char * Dstr = new char[2];
Dstr[0] = str[i];
Dstr[1] = str[i+D];
// printf("%c%c %d\n", Dstr[0], Dstr[1], (int)dset.size());
if ((it = dset.find(Dstr)) != dset.end()) {
// printf("XX %c%c\n", (*it)[0], (*it)[1]);
return 0;
} else {
dset.insert(Dstr);
}
}
}
}
return 1;
}
int main() {
char tmp[82];
while(scanf("%s", tmp) != EOF) {
if (!strcmp(tmp, "*")) {
return 0;
}
string str = tmp;
if (checkSurprising(str)) {
printf("%s is surprising.\n", tmp);
} else {
printf("%s is NOT surprising.\n", tmp);
}
}
}
水题,但是因为生疏了STL set的用法,以及string浅拷贝的问题,还是出了些问题,这道题用来检验C++的知识还是不错的。
首先是忘了STL set怎么判断元素相等:
一开始每次循环搞一个string, 然后做判断,insert进去,
后来发现个怪事,在某次循环对此string进行修改,会直接反应到已经存入set的string,刚开始时,还怀疑set难道不是拷贝插入,后来确认了下,确实是拷贝插入的,
最后搞清楚了原因,在循环定义的局部变量,在每次循环上,应该用的都是同样的地址,比如,
for(int i = 1; i <= 2; i++) {
int a;
}
那么么,这两次循环中,a的地址都是一样的,这样,如果把 a 换成string型的,
虽然每次都是拷贝string插入了set,但是因为string的实际内容是作为指针标示在string里的,而又因为每次string的内存地址都是一样的,
因此,修改该string,就修改了指针指向的内容,而在set中的string,指针也是指向这块内容,因此就反应到已经进入set的string了,因为string在拷贝插入set中是浅拷贝,
这里,因为局部变量的地址一直不变,某种意义上像一个引用.
以后复习下 efficitive STL 和 STL源码剖析吧,局部变量这个,是C++规范没有定义的地方,因此取决与编译器的,不过貌似主流的都是重复利用了地址。