ZOJ Problem Set–1151 Word Reversal
Time Limit: 2 Seconds Memory Limit: 65536 KB
For each list of words, output a line with each word reversed without changing the order of the words.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Input
You will be given a number of test cases. The first line contains a positive integer indicating the number of cases to follow. Each case is given on a line containing a list of words separated by one space, and each word contains only uppercase and lowercase letters.
Output
For each test case, print the output on one line.
Sample Input
1
3
I am happy today
To be or not to be
I want to win the practice contest
Sample Output
I ma yppah yadot
oT eb ro ton ot eb
I tnaw ot niw eht ecitcarp tsetnoc
Source: East Central North America 1999, Practice
这是一道考察输出格式控制的题目;其中reverse函数在VC 10.0中可以直接用,而在早一些的版本中,需要#include<algorithm>, 代码如下:
#include<iostream>#include<sstream>#include<algorithm>using namespace std;int main()
{int blocks;cin>>blocks;
for(int block = 0; block < blocks; block++){string state;
if(block == 0)//仅在第一次的时候有如下两个空行{getline(cin,state);//用getline 吃掉输入blocks之后的回车
getline(cin,state);//题目要求的空行
}int stateCount;cin>>stateCount;
getline(cin, state);while(stateCount--)
{getline(cin, state);istringstream is(state);string word;
int i = 0;
while(is>>word)
{reverse(word.begin(), word.end());if(i != 0)
cout<<" ";
cout<<word;i++;}cout<<endl;}if(block != blocks - 1)//最后一次输出没有空行{cout<<endl;}}return 0;
}
其中reverse函数是解决这道题的关键,在algorithm都文件中有定义。一下是我自己写的string的反序函数:
void ReverseString(string& str){size_t strLen = str.length();for(size_t i = 0; i < strLen/2;i++)
{str[i] = str[i]^str[strLen - i - 1];str[strLen - i - 1] = str[i]^str[strLen - i - 1];str[i] = str[i]^str[strLen - i - 1];}}
测试代码如下:
#include<iostream>#include<string>
using namespace std;void ReverseString(string& str){size_t strLen = str.length();for(size_t i = 0; i < strLen/2;i++)
{str[i] = str[i]^str[strLen - i - 1];str[strLen - i - 1] = str[i]^str[strLen - i - 1];str[i] = str[i]^str[strLen - i - 1];}}int main()
{string a = "abc";cout<<"Befor reverse , a is "<<a<<endl;
ReverseString(a);cout<<"After reverse, now a is "<<a<<endl;
return 0;
}
输出结果: