字符串排序III【北京大学考研机试题】

字符串排序III

按要求输入字符串进行排序并输出。

输入格式
输入包含多组测试数据。

每组测试数据,第一行包含整数 N,表示共有 N 个字符串。

接下来,会将这 N 个字符串,按一行一个的形式给出。

但是,逐个给出的过程中,有可能会直接输入一行 stop,表示该组数据停止输入,此时会直接开始下一组数据的输入。

也就是说,每组数据给出的字符串个数,可能不到 N 个。

另外,stop 不算给出的字符串。

输出格式
对于每组数据,将给出的所有字符串按长度由小到大排序输出。

每行输出一个字符串,注意不要将 stop 算在内。

数据范围
每个输入最多包含 100 个数据。
每组数据最多包含 100 个字符串,每个字符串的长度不超过 100,且不同字符串长度互不相同。

输入样例:
5
sky is grey
cold
very cold
stop
3
it is good enough to be proud of
good
it is quite good
输出样例:
cold
very cold
sky is grey
good
it is quite good
it is good enough to be proud of

代码

点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;

#define X first
#define Y second

typedef pair<int,int> pii;
typedef long long LL;
const char nl = '\n';
const int N = 1e6+10;
const int M = 2e5+10;
int n,m;

//多组测试数组->初始化
//

bool cmp(string a,string b){
	return a.size() < b.size();
}

void solve(){
	while(cin >> m){
		vector<string> v;
		string t;
        getline(cin,t); 
        //注意要先去除一行空行,getline会读入之前的'\n',而后面的'\n'会被读入并丢弃,因此不影响后面的getline
		while(m --){
			string s;
			getline(cin,s);
			if(s == "stop")break;
			v.push_back(s);
		}
		sort(v.begin(), v.end(),cmp);
		for(int i = 0; i <= v.size() - 1; i ++ ){
			cout << v[i];
			cout << nl;
		}
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);

	solve();
}

小结

  1. 注意要先去除一行空行,getline会读入之前的'\n',而后面的'\n'会被读入并丢弃,因此不影响后面的getline
posted @ 2023-03-06 16:54  Keith-  阅读(17)  评论(0编辑  收藏  举报