题目
题目描述
幼儿园两个班的小朋友在排队时混在了一起,每位小朋友都知道自己是否与前面一位小朋友同班,请你帮忙把同班的小朋友找出来。
小朋友的编号是整数,与前一位小朋友同班用Y表示,不同班用N表示。
输入描述
输入为空格分开的小朋友编号和是否同班标志。
比如:6/N 2/Y 3/N 4/Y,表示4位小朋友,2和6同班,3和2不同班,4和3同班。
其中,小朋友总数不超过999,每个小朋友编号大于0,小于等于999。
不考虑输入格式错误问题。
输出描述
输出为两行,每一行记录一个班小朋友的编号,编号用空格分开,且:
编号需按照大小升序排列,分班记录中第一个编号小的排在第一行。
若只有一个班的小朋友,第二行为空行。
若输入不符合要求,则直接输出字符串ERROR。
示例1
输入
1/N 2/Y 3/N 4/Y
输出
1 2
3 4
说明
2的同班标记为Y,因此和1同班。
3的同班标记为N,因此和1、2不同班。
4的同班标记为Y,因此和3同班。
所以1、2同班,3、4同班,输出为
1 2
3 4
示例2
输入
1/N 2/Y 3/N 4/Y 5/Y
输出
1 2
3 4 5
代码
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string line;
string item;
vector<vector<int>> students(2, vector<int>{});
int k = 0;
bool first = true;
getline(cin, line);
stringstream ss(line);
while (ss >> item)
{
size_t idx;
int student = stoi(item, &idx);
char nOrY = item[idx + 1];
if (first == true)
{
students[k].push_back(student);
first = false;
continue;
}
if ('Y' == nOrY)
{
students[k].push_back(student);
}
else if ('N' == nOrY)
{
k ^= 1;
students[k].push_back(student);
}
}
sort(students.begin(), students.end());
sort(students[0].begin(), students[0].end());
sort(students[1].begin(), students[1].end());
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < students[i].size(); j++)
{
cout << students[i][j] << " ";
}
cout << endl;
}
return 0;
}