C++
[C++] 백준 10825번: 국영수, 구조체 선언, 입력 자료형을 무시하지 말자
도비(Doby)
2021. 10. 1. 18:11
논리적으로는 쉬운 문제였다. 하지만, 내가 짜 놓은 논리와는 계속 엇나가는 출력이 나와서 1시간 동안 정렬할 때 쓴 compare 함수를 들여다보았지만 문제가 없는 듯했다.
(일부는 내가 원하는 대로 정렬하지만 일부는 논리를 엇나갔었다.)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(vector<string>& a, vector<string>& b) {
if (a[1] != b[1]) {
return a[1] > b[1];
}
else {
if ((a[1] == b[1]) && (a[2] != b[2])) {
return a[2] < b[2];
}
else {
if (((a[1] == b[1]) && (a[2] == b[2])) && (a[3] != b[3])) {
return a[3] > b[3];
}
else {
return a[0] < b[0];
}
}
}
}
int main() {
int n;
cin >> n;
vector<vector<string>> arr(n, vector<string>(4, "index"));
for (int i = 0; i < n; i++) {
string a, b, c, d;
cin >> a >> b >> c >> d;
arr[i][0] = a;
arr[i][1] = b;
arr[i][2] = c;
arr[i][3] = d;
}
sort(arr.begin(), arr.end(), cmp);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i][0] << '\n';
}
return 0;
}
그래서 게시판에서 도움을 얻었다.
https://www.acmicpc.net/board/view/39142
글 읽기 - 질문글 다 찾아보고 질문드립니다 ㅜㅠ 도와주세요
댓글을 작성하려면 로그인해야 합니다.
www.acmicpc.net
이 분이 나와 비슷한 부분에서 오류를 일으키는 거 같아 읽어보니 다 읽어보지 않아도 문제가 무엇이었는지 알 수 있었다.
이름은 string형에 담은 것이 좋았지만 점수는 그러면 되지 않았다.
(아무래도 잘못된 입력에 따라 다른 메모리를 건든 거 같다.) >> 정확한 근거 아님.
string형이라도 숫자끼리 비교가 가능했었기에 이 부분에 무지함이 있었던 거 같다.
그래서 student라는 구조체를 선언하여 입력에 각각 자료형이 맞도록 입력을 해주었다.
(a = name, b = kor, c = eng, d = math)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct {
string a;
int b, c, d;
} student;
bool cmp(student& a, student& b) {
if (a.b != b.b) {
return a.b > b.b;
}
else {
if ((a.b == b.b) && (a.c != b.c)) {
return a.c < b.c;
}
else {
if (((a.b == b.b) && (a.c == b.c)) && (a.d != b.d)) {
return a.d > b.d;
}
else {
return a.a < b.a;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<student> arr(n);
for (int i = 0; i < n; i++) {
string a;
int b, c, d;
cin >> a >> b >> c >> d;
arr[i].a = a;
arr[i].b = b;
arr[i].c = c;
arr[i].d = d;
}
sort(arr.begin(), arr.end(), cmp);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i].a << '\n';
}
return 0;
}
느낀 점
입력 자료형을 무시하지 말자! 절대!!