全部TLE到AC,只改了一处。
  • 板块P2814 家谱
  • 楼主yuyinruge
  • 当前回复12
  • 已保存回复12
  • 发布时间2020/8/15 21:35
  • 上次更新2023/11/6 20:10:29
查看原帖
全部TLE到AC,只改了一处。
158871
yuyinruge楼主2020/8/15 21:35

这题不难,但总是全部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;
}
2020/8/15 21:35
加载中...