这题不难,但总是全部TLE,改了一晚上,也考虑到用getchar( );读取垃圾字符'\n',在自己的编译器上运行成功,但是OJ就全部TLE。最后发现,必须用“while( getchar()!= '\n');”清空缓冲区才AC。可是不太清楚是为什么,请各位帮忙解答。
下面附上AC的代码:
#include <iostream>
#include <map>
#include <cstdio>
using namespace std;
map<string, string> p;
string find(string x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
string name, father;
char op;
while ((op = getchar())!= '$')
{
cin >> name;
while( getchar()!= '\n');
if (op == '#')
{
if(p[name] == "") p[name] = name;
father = name;
}
else if (op == '+') p[name] = father;
else
cout << name << ' ' << find(name) << endl;
}
return 0;
}