Member Pilot Round1 div2 medium
なかなか面白い問題で、人によって解き方多少違うと思う.
自分は(練習のために)キューを使いました.というか、キュー使わないと計算量がひどくなりそう.
e.g) A B C ERDOS B D D E F G ans:: A:1 B:1 C:1 D:2 E:3 F:3 G ERDOS:0
vectorcalculateNumbers(vector publications) { int sz = publications.size(); //co-authorship name list vector name; vector pos; for(int i = 0; i < sz; i++) { istringstream iss(publications[i]); string tmp; while(iss >> tmp) { name.push_back(tmp); pos.push_back(i); } } int num = name.size(); map rank; for(int i = 0; i < num; i++) { rank[name[i]] = -1; } queue que; que.push("ERDOS"); rank["ERDOS"] = 0; while(!que.empty() ) { string q = que.front(); que.pop(); vector ::iterator it = name.begin(); while((it = find(it, name.end(), q) ) != name.end()) { int p = it - name.begin(); istringstream iss(publications[pos[p]]); string s; while(iss >> s) { if(rank[s] != -1) continue; que.push(s); rank[s] = rank[q]+1; } it++; } } vector ans; map ::iterator it; for(it = rank.begin(); it != rank.end(); it++) { ostringstream oss; if(it->second == -1) { oss << (it->first); } else { oss << (it->first) << " " << (it->second); } ans.push_back(oss.str()); } return ans; }
流れとしては、 name -- pos rank[name]<--que ans ここで学んだことはfindの複数検索とか、幅検索の使い方とか.