홍시홍의 프로그래밍

[백준 1431] 시리얼 번호 본문

알고리즘 문제풀이/백준

[백준 1431] 시리얼 번호

홍시홍 2020. 2. 15. 14:38

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

 

1431번: 시리얼 번호

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

www.acmicpc.net

 

요구사항

조건 대로 정렬하기

 

풀이

merge를 구현하였다.

구조체로 합, 길이, str을 한군데 넣고 mer 구현

 

#include <iostream>
#include <string>

using namespace std;
struct go {
	int len;
	int sum;
	string str;
};

int n;
go map[1010];
go buf[1010];
void mer(go arr[], int len) {
	//cout << "B" << endl;
	if (len < 2) return;
	int i, j, mid, k;
	mid = len / 2;
	i = 0; j = mid; k = 0;
	mer(arr, mid);
	mer(arr + mid, len - mid);

	while (i < mid && j<len) {
	//	cout << "a" << endl;
		if (arr[i].len < arr[j].len) {
			buf[k++] = arr[i++];
		}
		else if (arr[i].len == arr[j].len) {
			if (arr[i].sum < arr[j].sum) {
				buf[k++] = arr[i++];
			}
			else if (arr[i].sum == arr[j].sum) {
				if (arr[i].str < arr[j].str) {
					buf[k++] = arr[i++];
				}
				else {
					buf[k++] = arr[j++];
				}
			}
			else {
				buf[k++] = arr[j++];
			}
		}
		else {
			buf[k++] = arr[j++];
		}
	}

	while (i < mid) {
	//	cout << "C" << endl;
		buf[k++] = arr[i++];
	}
	while (j < len) {
	//	cout << "D" << endl;
		buf[k++] = arr[j++];
	}
	for (int i = 0; i < len; i++) {
	//	cout << "E" << endl;
		arr[i] = buf[i];
	}
}
int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> map[i].str;
		map[i].len = map[i].str.length();
		map[i].sum = 0;
		for (int j = 0; j < map[i].len; j++) {
			int now = (int)(map[i].str.at(j));
			if (now >= 49 && now <= 57) {
				map[i].sum += (now - 48);
			}
		}
	}
	mer(map, n);
	for (int i = 0; i < n; i++) {
	//	cout << map[i].str << " " << map[i].len << " " << map[i].sum << endl;
		cout << map[i].str << endl;
	}
}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 2211] 네트워크 복구  (0) 2020.02.15
[백준 1213] 팰린드롬 만들기  (0) 2020.02.15
[백준 1936] 소수 경로  (0) 2020.02.13
[백준 16234] 인구 이동  (0) 2020.02.08
[백준 14890] 경사로  (0) 2020.02.08
Comments