PC/UVa:110206/10044
最开始这道题我用的深搜,但是uDebug的测试用例都要跑好久,后来改成了广搜。
按说这种典型算法是最不应该出错的,即使有错误那么WA个1~2次也知道问题在哪了,但是我WA了好多次。
然后找了一个跟我思路差不多的博客,用博主的程序往我的程序一点点靠近修改,最后才发现是输入数据的处理错了。
按照题目的描述,每个论文的作者分别先出现名,再出现姓,名后边是,
和空格,姓后边是.,
和空格,最后一个作者的姓后边是.:
,然后再一个空格后边是论文题目。根据上边出现的空格,分别将都入到strFirstName
和strLastName
中,如果strLastName
的末尾是:
,则表示作者已经读取完毕。这样的读取方式可以通过uDebug上的测试用例(100组测试数据那个),但是交了之后就是各种WA。
所以拆分作者应该使用.,
。
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
using namespace std;
vector<string> getAuthors(const string &strAuthor)
{
vector<string> vstrAuthors;
size_t begin = 0;
size_t end = strAuthor.find(".,", begin);
while (end != string::npos)
{
vstrAuthors.push_back(strAuthor.substr(begin, end + 1 - begin));
begin = end + 3;
end = strAuthor.find(".,", begin);
}
vstrAuthors.push_back(strAuthor.substr(begin));
return vstrAuthors;
}
void calErdosNum(map<string, int>& mstriErdos, const map<string, set<string>> &mstrsstrCop)
{
set<string> sstrInput, sstrUpdate;
mstriErdos["Erdos, P."] = 0;
sstrInput.insert("Erdos, P.");
int iErdos = 1;
while (1){
for (auto iterAuthor = sstrInput.begin(); iterAuthor != sstrInput.end(); iterAuthor++)
{
if (mstrsstrCop.find(*iterAuthor) != mstrsstrCop.end())
{
const set<string> &sstrCoper = mstrsstrCop.at(*iterAuthor);
for (auto iterCoper = sstrCoper.begin(); iterCoper != sstrCoper.end(); iterCoper++)
{
if (mstriErdos.find(*iterCoper) == mstriErdos.end()){
mstriErdos[*iterCoper] = iErdos;
sstrUpdate.insert(*iterCoper);
}
}
}
}
if (sstrUpdate.empty()) break;
iErdos++;
sstrInput = sstrUpdate;
sstrUpdate.clear();
}
}
int main()
{
int T = 0;
cin >> T;
for (int t = 0; t < T; t++)
{
int P = 0, N = 0;
cin >> P >> N;
cin.get();
map<string, int> mstriErdos;
map<string, set<string>> mstrsstrCop;
vector<string> vstrAuthor;
string strPaper;
for (int p = 0; p < P; p++)
{
getline(cin, strPaper);
vstrAuthor = getAuthors(strPaper.substr(0, strPaper.find_first_of(':')));
//存储合作关系
for (size_t i = 0; i < vstrAuthor.size(); i++)
{
for (size_t j = 0; j < vstrAuthor.size(); j++)
{
if (i != j){
mstrsstrCop[vstrAuthor[i]].insert(vstrAuthor[j]);
}
}
}
}
calErdosNum(mstriErdos, mstrsstrCop);
cout << "Scenario " << t + 1 << endl;
string strAuthor;
for (int n = 0; n < N; n++)
{
getline(cin, strAuthor);
cout << strAuthor << ' ';
auto iter = mstriErdos.find(strAuthor);
if (iter != mstriErdos.end()) cout << iter->second << endl;
else cout << "infinity" << endl;
}
}
return 0;
}
/*
1
4 3
Smith, M.N., Martin, G., Erdos, P.: Newtonian forms of prime factor matrices
Erdos, P., Reisig, W.: Stuttering in petri nets
Smith, M.N., Chen, X.: First oder derivates in structured programming
Jablonski, T., Hsueh, Z.: Selfstabilizing data structures
Smith, M.N.
Hsueh, Z.
Chen, X.
*/