๋ฌธ์ ํด๊ฒฐ (PS)/์ฝํ
TIL
[Java] ์ ๋ ฌ, ๊ทธ๋ฆฌ๋ | ๋ฐฑ์ค 1083 ์ํธ
9taetae9
2024. 11. 17. 10:15
728x90
https://www.acmicpc.net/problem/1083
์ ๊ทผ ๋ฐฉ๋ฒ :
๊ทธ๋ฆฌ๋ํ๊ฒ ๊ฐ ์์น์์ ํ์ฌ ๋ฒ์ ๋ด ๊ฐ์ฅ ํฐ ๊ฐ์ ์์ผ๋ก ์ด๋์ํจ๋ค.
- S์ ์ ํ ๋๋ฌธ์, ๊ฐ๋ฅํ ๊ตํ ํ์(j - i <= S)๋ฅผ ๊ณ ๋ คํด์ฃผ์ด์ผ ํ๋ค.
๋ ์์ ๊ตํ ๊ณผ์ :
- ํ์ฌ ์์น i ์์ i+1๋ถํฐ i+S๋ฒ์ ๋ด์์ ๊ฐ์ฅ ํฐ ๊ฐ์ ์ฐพ๋๋ค.
- ํด๋น ๊ฐ์ i๋ก ์ด๋์ํค๊ธฐ ์ํด ์ธ์ ์์ ๊ฐ ๊ตํ์ ๋ฐ๋ณตํ๋ค. (๋ฒ๋ธ ์ํธ์ ์ ์ฌ)
- ๊ฐ์ ์ด๋ ์ํค๋ ๋ฐ ์ฌ์ฉํ ๊ตํ ํ์๋งํผ S๋ฅผ ๊ฐ์์ํจ๋ค.
์ข ๋ฃ ์กฐ๊ฑด : S๊ฐ 0์ด ๋๊ฑฐ๋, ๋ฐฐ์ด์ ๋๊น์ง ํ์ํ์ ๊ฒฝ์ฐ ์ข ๋ฃ
ํต์ฌ ์ฝ๋
S ์ ํ ๋ด์์ ๊ฐ์ฅ ์ผ์ชฝ ์๋ฆฌ๋ถํฐ ์ต๋ ๊ฐ์ผ๋ก ์ฑ์์ฃผ๋ ๊ฒ์ ์ง์คํ๋ค.
๋งค ๋ฐ๋ณต ๋ง๋ค S-=(maxIndex - i); ๋ก ๊ตํํ ํ์๋งํผ S๋ฅผ ๊ฐ์์์ผ์ค๋ค.
private static void solve(){
for(int i=0; i<N; i++){
int maxIndex = i;
for(int j=i+1; j<N && j-i<=S; j++){
if(list.get(maxIndex) < list.get(j)){
maxIndex = j;
}
}
for(int j=maxIndex; j>i; j--){
Collections.swap(list, j, j-1);
}
S -= (maxIndex - i);
}
printList();
}
์ ์ฒด ์ฝ๋
public class BOJ1083 {
static List<Integer> list;
static int N,S;
public static void main(String[] args) throws Exception {
init();
solve();
}
private static void solve(){
for(int i=0; i<N; i++){
int maxIndex = i;
for(int j=i+1; j<N && j-i<=S; j++){
if(list.get(maxIndex) < list.get(j)){
maxIndex = j;
}
}
for(int j=maxIndex; j>i; j--){
Collections.swap(list, j, j-1);
}
S -= (maxIndex - i);
}
printList();
}
private static void printList(){
for(int e : list){
System.out.print(e+" ");
}
}
private static void init() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0; i<N; i++){
list.add(Integer.parseInt(st.nextToken()));
}
S = Integer.parseInt(br.readLine());
}
}
728x90