编程之美热身赛 传话游戏

来源:互联网 发布:域名历史记录查询 编辑:程序博客网 时间:2024/05/01 06:14

通过这道题发现我字符串的处理能力好差劲。上午写这道题发现读字符串的时候一直读不进去,后来在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;}


0 0
原创粉丝点击