现在发代码应该没什么问题,而且很多人都做出第一题,而且我的代码行数有点多啊。囧。。。
不过我的解决方法跟我看到的别人的代码不一样,我用了自己创建的结构体,结构体对象都存放在vector中,结构体中有一个string变量和一个int变量,int变量用来存放可能转变的下一个单词的标号,标号是指在vector中的位置。首先初始化的时候查找输入的单词是否存在vecotor中,然后进行插入或者对num值更新,初始化结束后,更具输入的语句对每个单词进行查找,如果在vector中,则通过循环,根据num值查找替换的单词,循环直到num为-1或者n=1结束;如果不在vecotr中,则直接输出。
我自认为我的这个方法在查找替换的时候不用每次替换都通过循环查找,而是直接通过下标进行。在这个步骤上效率应该比较高。
Ps:我昨晚一直提交都是WA,搞得我差点放弃了,因为用小数据输出的结果是正确的,知道后来才发现,原来是测试第二组数据的时候vector对象忘记clear了,小数据的话直接对前面的值进行覆盖,所以看不出错,但数据变化情况一多,就出问题了。。。这种细节果然教训深刻。。
代码如下:
#include <iostream> #include <string> #include <vector> using namespace std; struct vecstr { string str; int num; }; string int2str( int num) { if (num == 0 ) return "0" ; string str = "" ; int num_ = num > 0 ? num : - 1 * num; while (num_) { str = ( char )(num_ % 10 + 48 ) + str; num_ /= 10 ; } if (num < 0 ) str = "-" + str; return str; } int main() { int t; int n,m,c=1; string str1,str2,strall; vector<vecstr> strvec; cin>>t; while(c<=t) { cin>>n>>m; strvec.clear(); while(m>0) { int num1=0,num2=0; bool b1=false,b2=false; cin>>str1>>str2; vecstr a1,a2; a1.str = str1; a1.num = -1; a2.str = str2; a2.num = -1; for(unsigned int i=0;i<strvec.size();i++) { if(strvec[i].str==str1||b1) { if(!b1) num1 = i; b1 = true; } else num1++; if(strvec[i].str==str2||b2) { if(!b2) num2 = i; b2 = true; } else num2++; if(b1&&b2) break; } if(b1==true&&b2==true) strvec[num1].num = num2; else if(b1==true&&b2==false) { strvec.push_back(a2); strvec[num1].num = num2; } else if(b1==false&&b2==true) { strvec.push_back(a1); strvec[num1].num = num2; } else { strvec.push_back(a1); strvec.push_back(a2); strvec[num1].num = num2+1; } m--; } cin.ignore(); getline(cin,strall); int kongge2 = strall.find(' '); int kongge1 = 0; string out = ""; string word = strall.substr(kongge1,kongge2); while (word!="") { for(unsigned int i=0;i<strvec.size();i++) { if(strvec[i].str==word) { int n1 = n; int i1 = i; while(strvec[i1].num!=-1&&n1>1) { i1 = strvec[i1].num; word = strvec[i1].str; n1--; } i = strvec.size(); } } out = out + " " +word; if(kongge2==-1) break; strall = strall.substr(kongge2+1); kongge2 = strall.find(' '); if(kongge2==-1) word = strall.substr(kongge1); else word = strall.substr(kongge1,kongge2); } out = "Case #"+int2str(c) + ":"+ out; c++; cout<<out<<endl; } return 0; }