제민

1071 소트 본문

코테연습일지/그리디

1071 소트

jemin0619 2024. 4. 27. 20:15

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

 

풀이 참고

https://sunrinnote.tistory.com/143

https://velog.io/@bgg01578/%EB%B0%B1%EC%A4%80-1071-%EC%86%8C%ED%8A%B8

https://oculis.tistory.com/120

 

백준 1071, 소트

개요 문제 링크 플래 5, Greedy a[i+1] != a[i]+1이면서 사전순으로 가장 앞서게 정렬하기 접근 그리디한 인간이 되자. 수를 꺼내서 출력한다고 생각할 때, 가장 작은수부터 꺼내는 것이 가장 유리하다.

oculis.tistory.com

 

백준 1071 소트

문제링크 https://www.acmicpc.net/problem/1071 문제 풀이 배열을 오름차순으로 정렬시켜준다. v[i]+1 == v[i+1] 인 경우 auto it = lower_bound로 v[i]+2가 존재한다면 위치를 찾아준다. v[i]+2가 존재한다면 v[i]와 v[i+2]

velog.io

 

1071번 : 소트

https://www.acmicpc.net/problem/1071 1071번: 소트 N개의 정수가 주어지면, 이것을 연속된 두 수가 연속된 값이 아니게 정렬(A[i] + 1 ≠ A[i+1])하는 프로그램을 작성하시오. 가능한 것이 여러 가지라면 사전순

sunrinnote.tistory.com

 

코드

더보기
#include <bits/stdc++.h>
using namespace std;

int n;
vector<int> arr;
vector<bool> isused(53,false);

int main(){
    ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	cin>>n;
	for(int i=0;i<n;i++){
		int x; cin>>x;
		arr.push_back(x);
	} sort(arr.begin(),arr.end());

	int prev=-2;

	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			if(isused[j] || prev+1==arr[j]) continue;
			bool flag=true;
			for(int k=0;k<n;k++){
				//arr 배열에 arr[j]와 다른 값을 가진 값 중 arr[j]와 연속되지 않는 값을 갖는 요소가 있다면 flag=false;
				if(isused[k] || k==j || arr[k]==arr[j]) continue;
				if(arr[k]!=arr[j]+1) {flag=false; break;}
			}
			if(flag) continue;
			isused[j]=true;
			cout<<arr[j]<<' ';
			prev=arr[j];
			break;
		}
	}
	for(int i=0;i<n;i++) if(!isused[i]) cout<<arr[i]<<' ';
    return 0;
}