Google code jam: Problem B. Reverse Words

Problem

Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.

Input

The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.

Output

For each test case, output one line containing "Case #x: " followed by the list of words in reverse order.

Limits

Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000

Sample


Input
 

Output 
3
this is a test
foobar
all your base
Case #1: test a is this
Case #2: foobar
Case #3: base your all


我的代码:

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
//#define SMALL
#define LARGE
void main()
{
#ifdef SMALL
	freopen("B-small-practice.in","r",stdin);
	freopen("B-small-practice.out","w",stdout);
#endif

#ifdef LARGE
	freopen("B-large-practice.in","r",stdin);
	freopen("B-large-practice.out","w",stdout);
#endif
	string re_Line[1000];
	int N;
	cin>>N;
	char t;
	getchar(t);//No.1
	for(int i=0;i<N;i++)
	{
		string Line;
		char temp[1000];
		getline(cin,Line);//No.2
		int k=0,start=0;
		for(int j=0;j<Line.size();j++)
		{
			temp[j-start]=Line[j];
			if(Line[j]==' ')
			{
				temp[j-start]='\0';
				start=j+1;
				re_Line[k] = temp;
				k++;
			}
			if(j==Line.size()-1)
			{
				temp[j-start+1]='\0';
				re_Line[k] = temp;
				k++;
			}
		}
		cout<<"Case #"<<i+1<<": ";
		for(int count=k-1;count>=1;count--)
		{
			cout<<re_Line[count]<<' ';
		}
		cout<<re_Line[count]<<endl;
		
	}	
}

这道题主要考察的是对字符串的处理。在我的代码中用了C++标准库头文件定义的string类。大概思路是利用getline()函数读取一行,直到换行符。但是在之前输入N的时候,遗留了一个换行符在缓冲区了。如果直接用getline()的话,它遇到换行符就结束了,得到一个空字符串。所以在No.1的地方用了个getchar()清空缓冲区。然后再每一行读取字符串。读到了之后就遍历这个字符串,遇到空格就处理一下。然后最后面一个字符是没有空格的。注意下。


关于C++标准库申明头文件的时候是没有.h的,从C标准库继承过来的头文件可以在前面加c,比如ctype.h在C++标准库就是cctype。然后C++标准库需要申明这个头文件的命名空间 std

你可能感兴趣的:(Google code jam: Problem B. Reverse Words)