특정 알고리즘 필요없는 구현 문제이고, 배열 공부에 좋은 문제라고 생각되네요.

난이도는 실버1~골드5정도라고 느껴지네요. 쉽네요. 

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

 

16935번: 배열 돌리기 3

크기가 N×M인 배열이 있을 때, 배열에 연산을 R번 적용하려고 한다. 연산은 총 6가지가 있다. 1번 연산은 배열을 상하 반전시키는 연산이다. 1 6 2 9 8 4 → 4 2 9 3 1 8 7 2 6 9 8 2 → 9 2 3 6 1 5 1 8 3 4 2 9 →

www.acmicpc.net


import java.util.*;
import java.util.*;
import java.io.*;

public class Main {
	public static int[][]map;
	public static int[][]copymap;
	public static int n;
	public static int m;
	
    
	public static void updown() {
		
    	copymap=new int[n][m];
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				copymap[n-1-i][j]=map[i][j];
			}
		}
		
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				map[i][j]=copymap[i][j];
			}
		}
	}
	
	public static void rightleft() {
		
    	copymap=new int[n][m];
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				copymap[i][m-1-j]=map[i][j];
			}
		}
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				map[i][j]=copymap[i][j];
			}
		}
	}
	
	public static void angleRight() {
	
    	copymap=new int[m][n];
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			copymap[ j ][ n-1-i ]=map[ i ][ j ];
    		}
    	}
    	
    	
    	
    	int tmp =m;
		m=n;
		n=tmp;
		
		//n,m
		map=new int[n][m];
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				map[ i ][ j ]=copymap[ i ][ j ];
			}
		}
	}
	
	public static void angleLeft() {
	
    	copymap=new int[m][n];
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			copymap[ m-1-j ][ i ]=map[ i ][ j ];
    		}
    	}
    	
    	
    	
    	int tmp =m;
		m=n;
		n=tmp;
		
		//n,m
		map = new int[n][m];
		
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				map[ i ][ j ]=copymap[ i ][ j ];
			}
		}
		
	}
	
	public static void clockRight() {
		int tmpn=n/2;
		int tmpm=m/2; // 6 3
				
    	copymap=new int[n][m];
    	//1->2
    	for(int i=0;i<tmpn;i++) {
    		for(int j=0;j<tmpm;j++) {
    			copymap[ i ][ j+tmpm ]=map[i][j];
    		}
    	}
    	
    	//2->3
    	for(int i=0;i<tmpn;i++) {
    		for(int j=tmpm;j<m;j++) {
    			copymap[ i+tmpn ][ j ]=map[i][j];
    		}
    	}
    	
    	//3->4
    	for(int i=tmpn;i<n;i++) {
    		for(int j=tmpm;j<m;j++) {
    			copymap[ i ][ j-tmpm ]=map[i][j];
    		}
    	}
    	
    	//4->1
    	for(int i=tmpn;i<n;i++) {
    		for(int j=0;j<tmpm;j++) {
    		 copymap[ i-tmpn ][ j ]=map[i][j];
    		}
    	}
    	
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			map[i][j]=copymap[i][j];
    		}
    	}
	
	}
	public static void clockLeft() {
		int tmpn=n/2;
		int tmpm=m/2;
				
    	copymap=new int[n][m];
    	//1->4
    	for(int i=0;i<tmpn;i++) {
    		for(int j=0;j<tmpm;j++) {
    			copymap[ i+tmpn ][ j ]=map[ i ][ j ];
    		}
    	}
    	
    	//4->3
    	for(int i=tmpn;i<n;i++) {
    		for(int j=0;j<tmpm;j++) {
    			copymap[ i ][ j + tmpm ]=map[ i ][ j ];
    		}
    	}
    	
    	//3->2
    	for(int i=tmpn;i<n;i++) {
    		for(int j=tmpm;j<m;j++) {
    			copymap[ i-tmpn ][ j ]=map[i][j];
    		}
    	}
    	
    	//2->1
    	for(int i=0;i<tmpn;i++) {
    		for(int j=tmpm;j<m;j++) {
    			copymap[ i ][ j - tmpm ]=map[i][j];
    		}
    	}
    	
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			map[i][j]=copymap[i][j];
    		}
    	}
	}
	
	public static void prints() {
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				System.out.print(map[i][j]+" ");
			}
			System.out.println();
		}
	}
    public static void main(String[] args) throws IOException {
    	Scanner scan=new Scanner(System.in);
    	 n=scan.nextInt();
    	 m=scan.nextInt();
    	int k=scan.nextInt();
    	
    	map=new int[n][m];
    	
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			int tmp=scan.nextInt();
    			map[i][j]=tmp;
    		}
    	}
    	
    	for(int z=0;z<k;z++) {
    		int command=scan.nextInt();
    		switch (command) {
			case 1:
				
				updown();
				break;
			case 2:
				rightleft();
				break;
			case 3:
				angleRight() ;
				break;
			case 4:
				angleLeft();
				break;
			case 5:
				clockRight();
				break;
			case 6:
				clockLeft();
				break;

			default:
				break;
			}
    		
    	}
    	prints();
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 -탑  (0) 2024.03.30
백준 배열돌리기4  (0) 2024.03.30
백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17

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

 

20056번: 마법사 상어와 파이어볼

첫째 줄에 N, M, K가 주어진다. 둘째 줄부터 M개의 줄에 파이어볼의 정보가 한 줄에 하나씩 주어진다. 파이어볼의 정보는 다섯 정수 ri, ci, mi, si, di로 이루어져 있다. 서로 다른 두 파이어볼의 위치

www.acmicpc.net

이번주 연휴여서  가족끼리 간단히 여행다녀와서 주말에 공부를 많이 못했습니다.

 

여기서 핵심 포인트는 파이어볼이 나눠질때 나눠지는 순간에는 움직이지 않는다는 점을 주의 해야합니다.

그걸 모르면 음 나눠질때도 움직이게 계산을 하는 실수를 범할수 있습니다. 

문제는 조금 많이 생각해야하는 문제네요.

package test01;
import java.util.*;
import java.util.*;
import java.io.*;

public class Main {
    static int N, M, K;
    static ArrayList<Fireball>[][] map;
    static int[] dr = {-1, -1, 0, 1, 1, 1, 0, -1};
    static int[] dc = {0, 1, 1, 1, 0, -1, -1, -1};

    public static class Fireball {
        int r, c, m, s, d;

        public Fireball(int r, int c, int m, int s, int d) {
            this.r = r;
            this.c = c;
            this.m = m;
            this.s = s;
            this.d = d;
        }
    }

    public static void main(String[] args) throws IOException {
       Scanner scan=new Scanner(System.in);
        N = scan.nextInt();
        M =  scan.nextInt();
        K =  scan.nextInt();

        map = new ArrayList[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                map[i][j] = new ArrayList<Fireball>();
            }
        }

        for (int i = 0; i < M; i++) {
           
            int r =  scan.nextInt()- 1;
            int c =  scan.nextInt() - 1;
            int m =  scan.nextInt();
            int s =  scan.nextInt();
            int d = scan.nextInt();
            map[r][c].add(new Fireball(r, c, m, s, d));
        }

        for (int k = 0; k < K; k++) {
            moveFireballs();
            DivideFireballs();
        }

        int result = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                for (Fireball f : map[i][j]) {
                    result += f.m;
                }
            }
        }

        System.out.println(result);
    }

    public static void moveFireballs() {
        ArrayList<Fireball>[][] newMap = new ArrayList[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                newMap[i][j] = new ArrayList<Fireball>();
            }
        }

        for (int r = 0; r < N; r++) {
            for (int c = 0; c < N; c++) {
            	for(int z=0;z<map[r][c].size();z++) {
            		Fireball f=map[r][c].get(z);
            		int nr = (f.r + dr[f.d] * f.s % N + N) % N;
                     int nc = (f.c + dc[f.d] * f.s % N + N) % N;
            		
            			newMap[nr][nc].add(new Fireball(nr, nc, f.m, f.s, f.d));
            		
            	
            	}
                
            }
        }

        map = newMap;
    }

    public static void DivideFireballs() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (map[i][j].size() > 1) {
                    int sumM = 0;
                    int sumS = 0;
                    boolean even = true; 
                    boolean odd = true;
                    for (Fireball f : map[i][j]) {
                        sumM += f.m;
                        sumS += f.s;
                        if (f.d % 2 == 0) odd = false;
                        else even = false;
                    }

                    int nm = sumM / 5;
                    int ns = sumS / map[i][j].size();
                    map[i][j].clear();
                    if (nm > 0) {
                        for (int d = 0; d < 8; d += 2) {
                            if (even || odd) {
                            	map[i][j].add(new Fireball(i, j, nm, ns, d));
                            } 
                            else {
                            	map[i][j].add(new Fireball(i, j, nm, ns, d + 1));
                            }
                        }
                    }
                }
            }
        }
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 배열돌리기4  (0) 2024.03.30
백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11

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

 

21610번: 마법사 상어와 비바라기

마법사 상어는 파이어볼, 토네이도, 파이어스톰, 물복사버그 마법을 할 수 있다. 오늘 새로 배운 마법은 비바라기이다. 비바라기를 시전하면 하늘에 비구름을 만들 수 있다. 오늘은 비바라기

www.acmicpc.net

음 요즘 계속 평일에 알고리즘을 못푸네요 ㅠㅠ 

어쩌다보니 주말에 좀 풀게 되었는데 상황이 그렇게되어서 평일에 피곤하기도 하공 ㅠㅠ 나름 문제 읽고 풀려고하면 12시가 넘어서 ㅠ 일단 그래도 주말에라도 알고리즘 틈틈히 풀면서 포트폴리오도 쌓도록 하겠습니다. 

이번 문제는 상당히 쉬웠습니다. 다만 조금 조건이 많은거 뺴곤 구현문제로써는 상당히 좋은문제라고 생각했습니다. ㅎㅎ 


import java.util.*;

public class Main {
	public static int maps[][];
	public static boolean bCheck[][];
	public static int n;
	public static ArrayList<Cloud>clouds=new ArrayList<>();
	public static class Cloud{
		private int x;
		private int y;
		public Cloud(int x,int y) {
			this.x=x;
			this.y=y;
		}
		
		public void update(int x,int y) {
			this.x=x;
			this.y=y;
		}
		
		public int x() {
			return this.x;
		}
		
		public int y() {
			return this.y;
		}
	}
	public static void Prints() {
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				System.out.print(maps[i][j]+",");
			}
			System.out.println();
		}
	}
	public static void moving(int movX,int movY, int S ) {
		
		for(int i=0;i<S;i++) {
			for(int j=0;j<clouds.size();j++) {
				int tmpX=clouds.get(j).x();
				int tmpY=clouds.get(j).y();
				
				//이동
				tmpX=tmpX+movX;
				tmpY=tmpY+movY;
				
				if(tmpX < 0 ) {
					tmpX=n-1;
				}
				
				if(tmpX>n-1) {
					tmpX=0;
				}
				
				if(tmpY < 0 ) {
					tmpY=n-1;
				}
				
				if(tmpY>n-1) {
					tmpY=0;
				}
				
				clouds.get(j).update(tmpX,tmpY);
			}
		
		}
		//rain
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			
			maps[tmpX][tmpY]=maps[tmpX][tmpY]+1;
			
		}
	
		//대각선 4개 방향에 따라 물잇을시
		int dirx[]= {-1,1,-1,1};
		int diry[]= {-1,-1,1,1};
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			bCheck[tmpX][tmpY]=true;
			
	
			//대각선 4개
			int tmpcnt=0;
			for(int j=0;j<4;j++) {
				int tmpDirX=tmpX+dirx[j];
				int tmpDirY=tmpY+diry[j];
				if(tmpDirX  == -1 ||tmpDirY == -1 || tmpDirX>n-1 ||tmpDirY>n-1) {
					continue;
				}
				if(maps[tmpDirX][tmpDirY]<=0) {
					continue;
				}
				tmpcnt++;
			}
			
			maps[tmpX][tmpY]=maps[tmpX][tmpY]+tmpcnt;
			
		}
		
		
		
		ArrayList<Cloud>tmpClouds=new ArrayList<>();
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(maps[i][j]>=2 && bCheck[i][j] == false) {
					
					tmpClouds.add(new Cloud(i,j));
					//bCheck[i][j]=true;
					maps[i][j]=maps[i][j]-2;
					
				}
			}
		}
		
		
	   //clouds.clear();
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			bCheck[tmpX][tmpY]=false;
		}
		
		clouds.clear();
		
		for(int i=0;i<tmpClouds.size();i++) {
			clouds.add(tmpClouds.get(i));
		}
	}
	
	
    public static void main(String[] args) throws Exception {
    	
    	Scanner scan=new Scanner(System.in);
    	n=scan.nextInt();
    	int m=scan.nextInt();
    	
    	//1부터 순서대로 ←, ↖, ↑, ↗, →, ↘, ↓, ↙
    	
    	maps=new int[n][n];
    	bCheck=new boolean[n][n];
    	
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<n;j++) {
    			int tmp = scan.nextInt();
    			maps[i][j]=tmp;
    		}
    	}
    	//비바라기를 시전하면 (N, 1), (N, 2), (N-1, 1), (N-1, 2)에 비구름

    	clouds.add(new Cloud(n-1,0));// (N, 1)
    	clouds.add(new Cloud(n-1,1));//(N, 2)
    	clouds.add(new Cloud(n-2,0));//(N-1, 1)
    	clouds.add(new Cloud(n-2,1));// (N-1, 2)
    	
    	
    	for(int z=0;z<m;z++) {
    		int d=scan.nextInt();
    		int s=scan.nextInt();
    		
    		switch(d) {
    		case 1:  // ←
    			moving( 0, -1, s );
    			break;
    		case 2:   // ↖
    			moving( -1, -1, s );
    			break;
    		case 3:     //↑
    			moving( -1, 0, s );
    			break;
    		case 4:     //↗
    			moving( -1, 1, s );
    			break;
    		case 5:    // →
    			moving( 0, 1, s );
    			break;
    		case 6:    // ↘
    			moving( 1, 1, s );
    			break;
    		case 7:  //↓
    			moving( 1, 0, s );
    			break;
    		case 8:   //↙
    			moving( 1, -1, s );
    			break;
    			
    		default:
    			break;
    		}
    		
    	}
    	
    	int sum=0;
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<n;j++) {
    			sum=sum+maps[i][j];
    		}
    	}
    	System.out.println(sum);
        
    }
    
}

'알고리즘 공부' 카테고리의 다른 글

백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11
백준 미로 만들기  (1) 2024.02.02

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

 

20055번: 컨베이어 벨트 위의 로봇

길이가 N인 컨베이어 벨트가 있고, 길이가 2N인 벨트가 이 컨베이어 벨트를 위아래로 감싸며 돌고 있다. 벨트는 길이 1 간격으로 2N개의 칸으로 나뉘어져 있으며, 각 칸에는 아래 그림과 같이 1부

www.acmicpc.net

문제는 쉬운편이였습니다. 다만 문제를 이해하는게 조금 난이도가 있었고요 로봇을 내리는 상황을 정확하게 이해해야합니다. n번째의 로봇이 내린다. 라는걸 이해를 잘 해야합니다.

import java.util.*;

public class Main {
    private int durability;
    private boolean robot;

    public Main(int durability, boolean robot) {
        this.durability = durability;
        this.robot = robot;
    }

    public void setDurability(int durability) {
        this.durability = durability;
    }

    public void setRobot(boolean robot) {
        this.robot = robot;
    }

    public int getDurability() {
        return this.durability;
    }

    public boolean hasRobot() {
        return this.robot;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int k = scan.nextInt();

        Main belt[] = new Main[n * 2];

        for (int i = 0; i < n * 2; i++) {
            int tmp = scan.nextInt();
            belt[i] = new Main(tmp, false);
        }

        int gcnt = 0;
        while (true) {
            // Step 1: Move the belt
            Main tmp = belt[n * 2 - 1];
            for (int i = n * 2 - 1; i > 0; i--) {
                belt[i] = belt[i - 1];
            }
            belt[0] = tmp;

            // Step 1.5: Remove robot at position n-1 (if any)
            belt[n - 1].setRobot(false);

            // Step 2: Move the robots
            for (int i = n - 2; i >= 0; i--) { // 로봇 이동 가능성 검사 범위 수정
                if (belt[i].hasRobot() && !belt[i + 1].hasRobot() && belt[i + 1].getDurability() > 0) {
                    belt[i].setRobot(false);
                    belt[i + 1].setRobot(true);
                    belt[i + 1].setDurability(belt[i + 1].getDurability() - 1);
                    if (i + 1 == n - 1) { // n-1 위치에 도달한 로봇 즉시 내리기
                        belt[i + 1].setRobot(false);
                    }
                }
            }


            // Step 3: Add a new robot
            if (belt[0].getDurability() > 0 && !belt[0].hasRobot()) {
                belt[0].setRobot(true);
                belt[0].setDurability(belt[0].getDurability() - 1);
            }

            // Step 4: Check for broken belts
            int brokenCount = 0;
            for (Main m : belt) {
                if (m.getDurability() == 0) {
                    brokenCount++;
                }
            }

            gcnt++;
            if (brokenCount >= k) {
                System.out.println(gcnt);
                break;
            }
        }
        
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 빗물  (0) 2024.02.11
백준 미로 만들기  (1) 2024.02.02
백준 괄호의 값  (1) 2024.01.24

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

 

14719번: 빗물

첫 번째 줄에는 2차원 세계의 세로 길이 H과 2차원 세계의 가로 길이 W가 주어진다. (1 ≤ H, W ≤ 500) 두 번째 줄에는 블록이 쌓인 높이를 의미하는 0이상 H이하의 정수가 2차원 세계의 맨 왼쪽 위치

www.acmicpc.net

설이라 좀 많이 쉬었네요 ㅎㅎ 

그 뭔가 이 문젠 구현 문제보단 그리드문제에 좀더 가까운것같네요... 어렵더군요 ㅠ 

키 포인트는 가장 왼쪽벽, 가장 오른쪽 큰벽을 구한다음에 현재 블록에서 두개의 왼,오른쪽의 높은값중 가장 낮은 높이차를 구한후 합하는게 포인트입니다.

package test01;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
    	
    	Scanner scan=new Scanner(System.in);
        	int h=scan.nextInt();//4
        	int w=scan.nextInt();//8
        	int block[]=new int[w];
        	int start=0;
        	int end=0;
        	int min=0;
        	for(int i=0;i<w;i++) {
        		block[i]=scan.nextInt();
        	}
        	 int answer = 0;
        	
        	 for (int i = 1; i < w - 1; i++) {
                 int leftMax = 0;
                 int rightMax = 0;
                 
                 for (int j = 0; j < i; j++) {
                     leftMax = Math.max(leftMax, block[j]);
                 }

                 for (int j = i + 1; j < w; j++) {
                     rightMax = Math.max(rightMax, block[j]);
                 }

                 int water = Math.min(leftMax, rightMax) - block[i];
                 if (water > 0) {
                     answer += water;
                 }
             }
             System.out.println(answer);
        
    }
    
}

'알고리즘 공부' 카테고리의 다른 글

백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 미로 만들기  (1) 2024.02.02
백준 괄호의 값  (1) 2024.01.24
백준 톱니바퀴  (0) 2024.01.17

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

 

2665번: 미로만들기

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

www.acmicpc.net

 

다이크스트라를 이해하고 잇어야 쉽게 풀었겟네요.

 

한 5일정도 풀다가 더이상 안풀려서 대학때 배운 다이크스트라 다시 보니 좀 이해가 되네요 ㅠ 

으휴 ㅠ 다음에 비슷한문제로 좀 풀어봐야겟네요 ㅠ 

import java.util.*;

public class Main {
    private int x;
    private int y;

    public Main(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.nextLine(); 

        int[] dx = {1, -1, 0, 0};
        int[] dy = {0, 0, 1, -1};
        int[][] maps = new int[n][n];
        int[][] dist = new int[n][n];

        for (int i = 0; i < n; i++) {
            String tmp = scan.nextLine();
            for (int j = 0; j < tmp.length(); j++) {
                maps[i][j] = tmp.charAt(j) - '0';
                dist[i][j] = -1;
            }
        }

        Queue<Main> queue = new LinkedList<>();
        queue.add(new Main(0, 0));
        dist[0][0] = 0; 

        while (!queue.isEmpty()) {
            Main current = queue.poll();

            for (int i = 0; i < 4; i++) {
                int tmpDiri = current.getX() + dx[i];
                int tmpDirj = current.getY() + dy[i];

                if (tmpDiri < 0 || tmpDirj < 0 || tmpDiri >= n || tmpDirj >= n) {
                	continue; 
                } 

                int nextDist = dist[current.getX()][current.getY()];
                if (maps[tmpDiri][tmpDirj] == 0) {
                	nextDist += 1; 
                }

                if (dist[tmpDiri][tmpDirj] == -1 || dist[tmpDiri][tmpDirj] > nextDist) {
                    dist[tmpDiri][tmpDirj] = nextDist;
                    queue.add(new Main(tmpDiri, tmpDirj));
                }
            }
        }

        System.out.println(dist[n - 1][n - 1]); 
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11
백준 괄호의 값  (1) 2024.01.24
백준 톱니바퀴  (0) 2024.01.17
백준 숨바꼭질4  (0) 2024.01.12

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

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일 X

www.acmicpc.net

이틀이나 걸렸네용 ㅠ 

그렇게 어려운건 아닌데 좀 헷갈리는 문제네요.


import java.util.*;

public class Main {
    public static void main(String[] args) {
    	//한쌍의 괄호 (), []
    	//만일 x 가 올바른 괄호열 '(x)' 이나 [x] 도 ㅇ모두 올바른 괄호열이다
    	Scanner scan=new Scanner(System.in);
    	String str=scan.nextLine();
    	
    	//ArrayList<Character>stack=new ArrayList<>();
    	Stack<Character> stack=new Stack<>();
    	Stack<Character> sign=new Stack<>();
    	Stack<Character> anw=new Stack<>();
    	char pre='v';
    	boolean bCheck=false;
    	int sum=1;
    	int anws=0;
    	boolean isValid = true;
    	for(int i=0;i<str.length();i++) {
    		char c = str.charAt(i);
    		
    		if(c=='(' || c=='[') {
    			stack.add(c);
    			if(c=='(') {
    				sum=sum*2;
    			}
    			else {
    				sum=sum*3;
    			}
    			bCheck=true;
    			
    		}else {
    			
    			if(stack.isEmpty()) {
    				anws=0;
    				i=str.length()+1;
    				continue;
    			}
    			
    			char tmp=stack.peek();
    			stack.pop();
    			
    			if(c==')'&& tmp!='(') {
    				anws=0;
    				i=str.length()+1;
    				continue;
    			}
    			else if(c==']'&&tmp!='[') {
    				anws=0;
    				i=str.length()+1;
    				continue;
    			}
    			
    			if(bCheck==true) {
    				anws+=sum;
    			}
    			
    			if(c==')') {
    				sum=sum/2;
    			}else if(c==']') {
    				sum=sum/3;
    			}
    			
    			
    			bCheck=false;
    		}
    	}
    	if (!stack.isEmpty()) isValid = false;

        System.out.println(isValid ? anws : 0);

    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 빗물  (0) 2024.02.11
백준 미로 만들기  (1) 2024.02.02
백준 톱니바퀴  (0) 2024.01.17
백준 숨바꼭질4  (0) 2024.01.12
백준 미세먼지 안녕!  (1) 2024.01.06

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

 

14891번: 톱니바퀴

첫째 줄에 1번 톱니바퀴의 상태, 둘째 줄에 2번 톱니바퀴의 상태, 셋째 줄에 3번 톱니바퀴의 상태, 넷째 줄에 4번 톱니바퀴의 상태가 주어진다. 상태는 8개의 정수로 이루어져 있고, 12시방향부터

www.acmicpc.net

3일이나 걸렷네요 ㅠ 

package test01;

import java.util.Scanner;

public class Main {
    private static int[][] gears = new int[4][8];

    // 톱니바퀴를 시계 방향으로 회전
    public static void reverseClocks(int gearNum) {
        int firstnum = gears[gearNum][0];
        for (int j = 1; j < 8; j++) {
            gears[gearNum][j - 1] = gears[gearNum][j];
        }
        gears[gearNum][7] = firstnum;
    }

    // 톱니바퀴를 반시계 방향으로 회전
    public static void clocks(int gearNum) {
        int lastnum = gears[gearNum][7];
        for (int j = 7; j > 0; j--) {
            gears[gearNum][j] = gears[gearNum][j - 1];
        }
        gears[gearNum][0] = lastnum;
    }

    // 톱니바퀴 상태 출력
    public static void Prints() {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 8; j++) {
                System.out.print(gears[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }

    // 점수 계산
    public static void Score() {
        int sc = 0;
        for (int i = 0; i < 4; i++) {
            if (gears[i][0] == 1) {
                sc += (1 << i);
            }
        }
        System.out.println(sc);
    }

    // 주어진 방향에 따라 톱니바퀴 이동 확인
    public static void checkingmove(int num, int dir, boolean[] visited) {
        if (num < 0 || num > 3) {
            return;
        }

        visited[num] = true;

        if (num > 0 && !visited[num - 1]) {
            if (gears[num][6] != gears[num - 1][2]) {
                checkingmove(num - 1, -dir, visited);
            }
        }

        if (num < 3 && !visited[num + 1]) {
            if (gears[num][2] != gears[num + 1][6]) {
                checkingmove(num + 1, -dir, visited);
            }
        }

        if (dir == 1) {
            clocks(num);
        } else {
            reverseClocks(num);
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // 사용자 입력을 통한 톱니바퀴 상태 설정
        for (int i = 0; i < 4; i++) {
            String str = scan.nextLine();
            for (int j = 0; j < str.length(); j++) {
                gears[i][j] = str.charAt(j) - '0';
            }
        }
      //  Prints();

        // 회전 명령의 횟수 입력 받기
        int k = scan.nextInt();
        for (int i = 0; i < k; i++) {
            int gearNum = scan.nextInt() - 1;
            int dir = scan.nextInt();
            boolean[] visited = new boolean[4];
            checkingmove(gearNum, dir, visited);
           // Prints();
        }
        Score();

        scan.close();
    }
}

 

'알고리즘 공부' 카테고리의 다른 글

백준 미로 만들기  (1) 2024.02.02
백준 괄호의 값  (1) 2024.01.24
백준 숨바꼭질4  (0) 2024.01.12
백준 미세먼지 안녕!  (1) 2024.01.06
백준 - 경쟁적 전염  (1) 2024.01.02

+ Recent posts