맘에 안드는 풀이입니다. 토크나이저를 연습하려고 굳이 빙빙 돌아갔는데 시간 초과가 발생했어요.
endl
을 사용해서 발생한 시간 초과입니다.#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <sstream>
using namespace std;
struct node {
int age;
int time;
string name;
};
bool comp(node a, node b) {
if (a.age == b.age) {
return a.time < b.time;
}
else
return a.age < b.age;
}
int main() {
int n;
cin >> n;
vector <node> arr;
cin.ignore(); // 공백, 엔터 같은 것을 무시
for (int i = 0; i < n; i++) {
// 입력 받기
string temp;
getline(cin, temp);
// 토크나이징 준비
stringstream str(temp);
string buffer;
struct node nd;
int idx = 0;
// tokenize (굳이 할 필요가 없는데..ㅠㅠ)
while (getline(str, buffer, ' ')) {
if (idx == 0) {
nd.age = stoi(buffer);
}
if (idx == 1) {
nd.name = buffer;
nd.time = i;
}
idx++;
}
arr.push_back(nd);
}
// 정렬
sort(arr.begin(), arr.end(), comp);
// 출력
for (int i = 0; i < n; i++) {
cout << arr[i].age <<" " << arr[i].name<< endl;
}
}
tokenizer를 체화하기 위해 연습으로 풀었으나 시간초과가 발생했습니다.
time 순으로 정렬하는 조건도 있어서 구조체를 직접 만들었습니다.
굉장히 비효율적으로 구문들을 나누고 있습니다.
stable_sort
를 이용하면 index가 유지된 채로 완전한 sort가 이루어짐을 학습을 통해 배웠습니다.input으로 들어오는 type이 정해져 있다면 cin으로 그에 맞게 받아주면 됩니다.
cout, cin을 최적화해줍시다.
출력이 많은 경우 endl 사용을 금지합니다.
시간이 오래걸립니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
bool comp(pair<int, string> a, pair<int, string> b) {
return a.first < b.first;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
pair<int, string> info;
vector<pair<int, string>> arr;
for (int i = 0; i < n; i++) {
cin >> info.first >> info.second;
arr.push_back(info);
}
stable_sort(arr.begin(), arr.end(),comp);
for (auto itr : arr) {
cout << itr.first << " " << itr.second << '\n';
}
return 0;
}