通過這道題發現我字串的處理能力好差勁。上午寫這道題發現讀字串的時候一直讀不進去,後來在getline前面加上了cin.get終於算是把字串讀進去了。後來就出現了亂碼的情況,然後發現是從字元賦值給字串的時候沒有結尾,就在string類型後面加上了一對奇怪的字元,加上限制語句以後就好了。然後就是提交一直WA。仔細檢查了以後發現是getline函數裡面設定了輸入字元的個數為100。剛開始想著題目中說每句話中字元的個數不超過100,然後突然明白題目中所說的這個東西是指不包含空格。然後把100改成了1000。接下來提交就是re。然後再檢查,發現題目中給出的M最大值是100,也就是單詞轉化列表長度為100行,最開始把圖的數組開了100*100的。但是每行裡面有倆單詞,也就是說最大可以有200個不同單詞。然後把圖的空間擴大,終於過了。。
代碼如下:
#include<iostream>#include<cstring>#include<vector>#include<cstdio>using namespace std;int graph[205][205];//最開始把數組開了105導致revector<string> words;int ID(const string name){string s(name);int n=words.size();for(int i=0;i<n;++i){if(s==words[i])return i;}words.push_back(name);return n;}int getID(const string word){string s(word);int n=words.size();for(int i=0;i<n;++i){if(s==words[i])return i;}return -1;}int main(){//freopen("data.txt","r",stdin);ios::sync_with_stdio(false);int T;cin>>T;int kace=0;while(T--){cout<<"Case #"<<++kace<<':'<<' ';words.clear();memset(graph,0,sizeof(graph));int n,m;cin>>n>>m;for(int i=0;i<m;++i){string from;string to;cin>>from>>to;int f=ID(from);int t=ID(to);graph[f][t]=1;}//for(int i=0;i<words.size();++i){//cout<<i<<' '<<words[i]<<endl;//}//for(int i=0;i<words.size();++i){//for(int t=0;t<words.size();++t){//cout<<graph[i][t]<<' ';//}//cout<<endl;//}char mes[105];for(int i=0;i<101;++i){mes[i]='\0';}cin.get();cin.getline(mes,1000);//這裡最開始是100,導致WAint tar=0;while(tar<strlen(mes)){string speak;speak.clear();while(mes[tar]!=' '&&mes[tar]!='\n'&&tar<strlen(mes)){//這裡一開始只有一個判斷條件mes[tar]!=' '導致了字串亂碼speak+=mes[tar];++tar;}int pos;for(int i=0;i<n-1;++i){pos=getID(speak);if(pos==-1){cout<<speak;break;}int findw=0;for(int t=0;t<words.size();++t){if(graph[pos][t]){findw=1;speak=words[t];pos=t;break;}}//cout<<"11speak="<<speak<<endl;if(!findw){cout<<speak;break;}if(i==n-2){cout<<speak;}}++tar;if(tar<strlen(mes))cout<<' ';}fflush(stdin);cout<<endl;}return 0;}