很久未曾刷题,凌晨睡不着,找了道比较简单的练下手,久违的AC感受,等这阵子忙完等级考试、比赛、论文的一堆破事,就全心投入刷题,准备PAT考试中去,再参加最后一次校赛。其实挺后悔没入校队的,真想到区域赛看看,真难过如今,想哭。往事已矣,立足当下,自勉,写完到A协睡觉去。ios
比赛描述编辑器
输入函数
多行,每行以 # 为结束,第1行为一段英文文字(单词数、数字很少于500),其他行是待搜索的英文短语(单词数很少于10)。这里英文文字、英文短语只包含英文单词,这些单词以空格分隔。测试
输出spa
多行,每一行对应输入中给定的短语在文字中出现的最后一个位置,搜索不到时输出-1。设计
样例输入code
STOCKHOLM April 21 PRNewswire FirstCall Students from St Petersburg State University of IT Mechanics and Optics are crowned the 2009 ACM International Collegiate Programming Contest World Champions in the Stockholm Concert Hall where the Nobel Prizes are presented every year Sponsored by IBM the competition took place today at KTH the Royal Institute of Technology #
STOCKHOLM #
St Petersburg State University of IT Mechanics and Optics #
World Champions #
the #
NUPT #内存
样例输出ci
1
8
26
51
-1字符串
题目来源
南京邮电大学计算机学院首届ACM程序设计大赛(2009)
好久没写,而后当头有点蒙其实,连 连续输入 都没想起来要怎么写,
思路就是:定义两个string字符串,origin保存输入的原始字符串,comp保存进行比较的字符串,调用string自带函数rfind(),判断comp到底在不在origin中,若是不在就直接输出-1,进行下一次循环;若是在,就去查找字符串的位置,主要是短语的位置。关于短语位置的求取,我是用的方法也比较常规,就是统计‘ ’ 空格个数,输出的时候加1就好了,不难理解。
代码:
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int len = 500 + 10; int main() { string origin; string comp; // freopen("datain.txt", "r", stdin); while(getline(cin, origin)) { origin = origin.substr(0,origin.length()-1); while(getline(cin, comp)) { comp = comp.substr(0,comp.length()-1); int hh = static_cast<int>(origin.rfind(comp)); if(hh == -1) { printf("-1\n"); } else { int cnt = 0; for(int i = 0; i <= hh; i++) { if(origin[i] == ' ') { cnt++; } } printf("%d\n",cnt + 1); } comp.clear(); } } }