1일1알

백준 1431번 시리얼 번호 C++ 본문

알고리즘

백준 1431번 시리얼 번호 C++

영춘권의달인 2023. 6. 21. 14:15

https://www.acmicpc.net/problem/1431

 

1431번: 시리얼 번호

첫째 줄에 기타의 개수 N이 주어진다. N은 50보다 작거나 같다. 둘째 줄부터 N개의 줄에 시리얼 번호가 하나씩 주어진다. 시리얼 번호의 길이는 최대 50이고, 알파벳 대문자 또는 숫자로만 이루어

www.acmicpc.net

 

MyStr 구조체에 비교연산자 재정의

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

struct MyStr {
	string str;
	bool operator<(const MyStr& other) const {
		if (str.length() == other.str.length()) {
			int mySum = 0;
			int otherSum = 0;
			for (int i = 0; i < str.length(); i++) {
				if (str[i] >= '0' && str[i] <= '9') {
					mySum += str[i] - '0';
				}
				if (other.str[i] >= '0' && other.str[i] <= '9') {
					otherSum += other.str[i] - '0';
				}
			}
			if (mySum == otherSum) {
				return str < other.str;
			}
			return mySum < otherSum;
		}
		return str.length() < other.str.length();
	}
};

vector<MyStr> v;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string str;
		cin >> str;
		v.push_back({str});
	}
	sort(v.begin(), v.end());
	for (auto a : v) {
		cout << a.str << "\n";
	}
};