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

20058번: 마법사 상어와 파이어스톰

마법사 상어는 파이어볼과 토네이도를 조합해 파이어스톰을 시전할 수 있다. 오늘은 파이어스톰을 크기가 2N × 2N인 격자로 나누어진 얼음판에서 연습하려고 한다. 위치 (r, c)는 격자의 r행 c

www.acmicpc.net

와 두번다시는 풀고 싶지는 않는문제네요
* 이후 얼음이 있는 칸 3개 또는 그 이상과 인접해있지 않은 칸은 얼음의 양이 1 줄어든다.
->3개 미만은 얼음이 줄어든다 (무슨 국어 문제인가.. ㅎ)
* 남아있는 얼음 중 가장 큰 덩어리가 차지하는 칸의 개수 얼음이 있는 칸이 얼음이 있는 칸과 인접해 있으면, 두 칸을 연결되어 있다고 한다. 덩어리는 연결된 칸의 집합
->연결된 얼음 덩어리들의 칸의 갯수의 합,즉 얼음은 bfs,dfs를 통해서 연결해서 얼음 덩어리들을 계산하라는 의미
 

import java.util.*;
import java.io.*;
import java.lang.*;
import java.io.*;
public class Main {
	public static int n;
	public static int q;
	public static int maps[][];
	public static int copyMaps[][];
	public static boolean bCheck[][];
	public static boolean initbCheck[][];
	public static boolean[][] visited; 
	public static int L;
	public static void prints(int tmpMap[][]){
		System.out.println();
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				System.out.print(tmpMap[i][j]+",");
			}
			System.out.println();
		}
	}
	public static class Ice {
		public int i;
		public int j;
		public Ice(int i,int j) {
			this.i=i;
			this.j=j;
		}
	}
	public static void Rotation(int starti, int startj){
		int cnt=1;
		int rStarti=starti*L;
		int rEndi=starti*L+L;
		int rStartj=startj*L;
		int rEndj=startj*L+L;

		int rLengthI=(rStarti+rEndi)/2;
		int rLengthJ=(rStartj+rEndj)/2;

		int rCountI=(rEndi-rStarti)/2;
		int rCountJ=(rEndi-rStarti)/2;

		//1 ->2
		for(int i=rStarti;i<rLengthI;i++){
			for(int j=rStartj;j<rLengthJ;j++){
				copyMaps[i][j+ rCountJ]=maps[i][j];
			}
		}
		//2->3
		for(int i=rStarti;i<rLengthI;i++){
			for(int j=rLengthJ;j<rEndj;j++){
				copyMaps[i+rCountI][j]=maps[i][j];
			}
		}

		//3->4
		for(int i=rLengthI;i<rEndi;i++){
			for(int j=rLengthJ ;j<rEndj;j++){
				copyMaps[i][j-rCountJ]=maps[i][j];
			}
		}
		//4->1
		for(int i=rLengthI;i<rEndi;i++){
			for(int j=rStartj;j<rLengthJ;j++){

				copyMaps[i-rCountI][j]=maps[i][j];
			}
		}
		//prints(copyMaps);
		
		

	}
	
	public static void Rotations(int starti, int startj) {
	    int rStarti = starti * L;
	    int rStartj = startj * L;
	    int[][] temp = new int[L][L];

	    for (int i = 0; i < L; i++) {
	        for (int j = 0; j < L; j++) {
	            temp[j][L - 1 - i] = maps[rStarti + i][rStartj + j];
	        }
	    }

	    for (int i = 0; i < L; i++) {
	        for (int j = 0; j < L; j++) {
	        	maps[rStarti + i][rStartj + j] = temp[i][j];
	        }
	    }
	}
	public static int bfs(int x, int y) {
	    if(maps[x][y] <= 0) return 0; 
	    int count = 1;
	    Queue<Ice> queue = new LinkedList<>();
	    queue.add(new Ice(x, y));
	    visited[x][y] = true;

	    while (!queue.isEmpty()) {
	        Ice current = queue.poll();
	        int i = current.i;
	        int j = current.j;

	        int[] di = {-1, 1, 0, 0}; 
	        int[] dj = {0, 0, -1, 1}; 

	        for (int k = 0; k < 4; k++) {
	            int ni = i + di[k];
	            int nj = j + dj[k];

	            if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && maps[ni][nj] > 0) {
	                queue.add(new Ice(ni, nj));
	                visited[ni][nj] = true;
	                count++; 
	            }
	        }
	    }
	    return count;
	}
	
	public static void main(String[] args) throws Exception {
		Scanner scan = new Scanner(System.in);
		n=scan.nextInt();
		q=scan.nextInt();
		double tmpn=Math.pow(2,n);
		n=(int)tmpn;
		maps=new int[n][n];
		copyMaps=new int[n][n];
		bCheck=new boolean[n][n];
		initbCheck=new boolean[n][n];
		visited = new boolean[n][n];

		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				maps[i][j]=scan.nextInt();
				copyMaps[i][j]=maps[i][j];
			}
		}
		for(int t=0;t<q;t++){
			
			L=scan.nextInt();

			double tmpL=Math.pow(2,L);
			L=(int)tmpL;
			//2x2
			//4x4
			//8x8
			int divide=n/L;
			
			
			for(int i=0;i<divide;i++){
				for(int j=0;j<divide;j++){
					Rotations(i,j);
				}
			}
			
			int diri[]= {-1,1,0,0};
			int dirj[]= {0,0,-1,1};
			
			ArrayList<Ice> saveIce=new ArrayList<>();
			for (int i = 0; i < n; i++) {
			    for (int j = 0; j < n; j++) {
			        int iceCnt = 0; 
			        for (int k = 0; k < 4; k++) {
			            int ni = i + diri[k];
			            int nj = j + dirj[k];
			            if (ni < 0 || nj < 0 || ni >= n || nj >= n) continue;
			           
			            if (maps[ni][nj] > 0) iceCnt++;
			        }
			        if (iceCnt < 3) {
			            saveIce.add(new Ice(i, j));
			        }
			    }
			}

			// 저장된 모든 칸의 얼음을 1 줄입니다.
			for (Ice ice : saveIce) {
			    maps[ice.i][ice.j] = Math.max(0, maps[ice.i][ice.j] - 1); 
			}
			
		}
		
		int sum=0;
		int maxs=0;
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(maps[i][j]>=0) {
					sum+=maps[i][j];
				}
				
			}
		}
		System.out.println(sum);
		int maxSizeOfIce = 0;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        if (!visited[i][j] && maps[i][j] > 0) {
            maxSizeOfIce = Math.max(maxSizeOfIce, bfs(i, j));
        }
    }
}
		System.out.println(maxSizeOfIce);
		//Rotation(0,1);

	}
}

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

백준 - 감시  (0) 2024.04.04
백준 배열과 연산  (0) 2024.04.04
백준 마법사 상어와 토네이도  (0) 2024.04.02
백준 최소 회의실 개수  (0) 2024.04.02
백준 배열돌리기2  (0) 2024.04.02

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

 

20057번: 마법사 상어와 토네이도

마법사 상어가 토네이도를 배웠고, 오늘은 토네이도를 크기가 N×N인 격자로 나누어진 모래밭에서 연습하려고 한다. 위치 (r, c)는 격자의 r행 c열을 의미하고, A[r][c]는 (r, c)에 있는 모래의 양을

www.acmicpc.net

골드3 문제인데..ㅋㅋ 두번 다시는 풀고 싶지않는 문제 생각을 좀 해야하네여 ㅎㅎ 

import java.util.*;
import java.io.*;
public class Main {
	public static int n;
	public static int maps[][];
	public static int copyMaps[][];
	public static int ci;
	public static int cj;
	public static int outsand=0;
	public static void Prints(int tmpmaps[][]){
		System.out.println();

		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				System.out.print(tmpmaps[i][j]+",");
			}
			System.out.println();
		}
		System.out.println();
	}
	public static void checking(int checki,int checkj,int input ){
		if(checki> n-1 ||checkj >n-1||checki<0||checkj<0){
			//System.out.println("sendout:"+input);
			outsand=outsand+input;

		}else{
			maps[checki][checkj] = maps[checki][checkj]+input;
		}
	}
	public static void spread(int mci,int mcj,int diri,int dirj,int index ,int pi,int pj){
		//Prints(maps);
		int tmp=maps[mci][mcj];
		maps[mci][mcj]=0;

		int two=  (int)(tmp*0.02);
		int one=  (int)(tmp*0.01);
		int seven=  (int)(tmp*0.07);
		int ten=  (int)(tmp*0.1);
		int five=  (int)(tmp*0.05);
		int alpa=tmp-(two*2+one*2+seven*2+ten*2+five);
		int alpai=mci+diri;
		int alpaj=mcj+dirj;
		/*
		System.out.println("alpa:"+alpa);
		System.out.println("two:"+two);
		System.out.println("seven:"+seven);
		System.out.println("ten:"+ten);
		System.out.println("five:"+five);
		System.out.println("five:"+one);*/
		checking(mci + diri * 2,mcj + dirj * 2, five );
		if(index==0){
			checking(mci+2,mcj, two );
			checking(mci-2,mcj, two );

			checking(alpai-1,alpaj, ten );
			checking(alpai+1,alpaj, ten );

			checking(mci-1,mcj, seven );
			checking(mci+1,mcj, seven );

			checking(pi-1,pj, one );
			checking(pi+1,pj, one );
		}else{
			checking(mci,mcj-2, two );
			checking(mci,mcj+2, two );

			checking(alpai,alpaj-1, ten );
			checking(alpai,alpaj+1, ten );

			checking(mci,mcj-1, seven );
			checking(mci,mcj+1, seven );

			checking(pi,pj-1, one );
			checking(pi,pj+1, one );
		}
		checking(alpai,alpaj, alpa );
		//Prints(maps);
	}
	public static void Rotation(int index){
			if(index%2==1){
				//left 0
				for(int i=0;i<index;i++){
					int tmpi=ci;
					int tmpj=cj;
					ci=ci;
					cj=cj-1;
					if(maps[ci][cj]>0){
						spread(ci,cj,0,-1,0,tmpi,tmpj);
					}
				}
				//copyMaps[][]=maps[ci][cj];
				// down 1
				for(int i=0;i<index;i++){
					int tmpi=ci;
					int tmpj=cj;
					ci=ci+1;
					cj=cj;
					if(maps[ci][cj]>0){
						spread(ci,cj,1,0,1,tmpi,tmpj);
					}
				}
			}else{
				//right 2
				for(int i=0;i<index;i++) {
					int tmpi=ci;
					int tmpj=cj;
					ci = ci;
					cj = cj + 1;
					if(maps[ci][cj]>0){
						spread(ci,cj,0,1,0,tmpi,tmpj);
					}
				}
				// up 3
				for(int i=0;i<index;i++) {
					int tmpi=ci;
					int tmpj=cj;
					ci = ci - 1;
					cj = cj;
					if(maps[ci][cj]>0){
						spread(ci,cj,-1,0,1,tmpi,tmpj);
					}
				}
			}

		//left 1 0
		//down 1 0
		//right 2 1
		//up 2 1
		//..
		//right 6
		//up 6

		//left 6
	}

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

		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				int tmp=scan.nextInt();
				maps[i][j]=tmp;
				copyMaps[i][j]=tmp;
			}
		}

		 ci=n/2;
		 cj=n/2;
		//System.out.println("center:"+ci+","+cj);
		for(int i=0;i<n-1;i++) {
			Rotation( i +1 );
		}
		//System.out.println("center:"+ci+","+cj);

		//last left
		for(int i=0;i<n-1;i++){
			int tmpi=ci;
			int tmpj=cj;
			ci=ci;
			cj=cj-1;
			if(maps[ci][cj]>0){
				spread(ci,cj,0,-1,0,tmpi,tmpj);
			}
		}
		//System.out.println("center:"+ci+","+cj);
		System.out.println(outsand);
	}
}

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

백준 배열과 연산  (0) 2024.04.04
백준 마법사 상어와 파이어스톰  (1) 2024.04.03
백준 최소 회의실 개수  (0) 2024.04.02
백준 배열돌리기2  (0) 2024.04.02
백준 0 만들기  (1) 2024.04.01

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

 

19598번: 최소 회의실 개수

서준이는 아빠로부터 N개의 회의를 모두 진행할 수 있는 최소 회의실 개수를 구하라는 미션을 받았다. 각 회의는 시작 시간과 끝나는 시간이 주어지고 한 회의실에서 동시에 두 개 이상의 회의

www.acmicpc.net

그리드 문제이고 우선순위 큐만 잘 커스텀하면 쉽게 푸는 문제네요.

import java.util.*;
import java.io.*;
public class Main {
	public static void Prints(PriorityQueue<Meetings>q){

	}
	public static class Meetings{
		public int start;
		public int end;
		public Meetings(int start, int end){
			this.start=start;
			this.end=end;
		}
	}
	public static void main(String[] args) throws Exception {
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		Comparator<Meetings> comparator =new Comparator<Meetings>(){
			@Override
			public int compare(Meetings m1, Meetings m2){
				if(m1.start<m2.start){
					return -1;
				}else if(m1.start>m2.start) {
					return 1;
				}
				return 0;
			}
		};
		Comparator<Meetings> comparator2 =new Comparator<Meetings>(){
			@Override
			public int compare(Meetings m1, Meetings m2){
				if(m1.end<m2.end){
					return -1;
				}else if(m1.end>m2.end) {
					return 1;
				}
				return 0;
			}
		};

		PriorityQueue<Meetings>q=new PriorityQueue<>(comparator);
		for(int i=0;i<n;i++){
			int start=scan.nextInt();
			int end=scan.nextInt();
			q.add(new Meetings(start,end));
		}

		PriorityQueue<Meetings>save=new PriorityQueue<>(comparator2);

		while (!q.isEmpty()){
			Meetings mstart=q.peek();
			q.poll();
			//System.out.println(mstart.start+","+mstart.end);
			//for(int i=0; i<save.size(); i++){
			if(save.size()>0){
				if( save.peek().end <= mstart.start ){
					save.poll();
					//	break;
				}
			}


			save.add(mstart);

		}
		System.out.println(save.size());
	}
}

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

백준 마법사 상어와 파이어스톰  (1) 2024.04.03
백준 마법사 상어와 토네이도  (0) 2024.04.02
백준 배열돌리기2  (0) 2024.04.02
백준 0 만들기  (1) 2024.04.01
백준 로봇 시뮬레이션  (1) 2024.04.01

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

 

16927번: 배열 돌리기 2

크기가 N×M인 배열이 있을 때, 배열을 돌려보려고 한다. 배열은 다음과 같이 반시계 방향으로 돌려야 한다. A[1][1] ← A[1][2] ← A[1][3] ← A[1][4] ← A[1][5] ↓ ↑ A[2][1] A[2][2] ← A[2][3] ← A[2][4] A[2][5]

www.acmicpc.net

흠 조금 시간이 걸렸네요 

키포인트는 

명령횟수가  10^9이어서 시간초과가 발생합니다. 그래서 회전의 경우 원복되는 상황은 그대로인걸 감안해서 %를 이용해서 횟수를 줄이면됩니다.

키포인트:

  int parms = (2 * (n - 2 * i) + 2 * (m - 2 * i) - 4);
            int rotations = k % parms;
package test01;
import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
    public static int[][] maps;
    public static int[][] copymaps;
    public static int n, m, k;

    public static void prtints(int[][] maps, int n, int m) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(maps[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void rotation(int startr, int endr, int startc, int endc) {
        // top
        for (int i = startc + 1; i <= endc; i++) {
            copymaps[startr][i - 1] = maps[startr][i];
        }
        // left
        for (int i = startr; i < endr; i++) {
            copymaps[i + 1][startc] = maps[i][startc];
        }
        // right
        for (int i = startr + 1; i <= endr; i++) {
            copymaps[i - 1][endc] = maps[i][endc];
        }
        // bottom
        for (int i = startc; i < endc; i++) {
            copymaps[endr][i + 1] = maps[endr][i];
        }
       
        for (int i = startr; i <= endr; i++) {
            for (int j = startc; j <= endc; j++) {
                maps[i][j] = copymaps[i][j];
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        n = scan.nextInt();
        m = scan.nextInt();
        k = scan.nextInt();
        maps = new int[n][m];
        copymaps = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int tmp = scan.nextInt();
                maps[i][j] = tmp;
                copymaps[i][j] = tmp;
            }
        }

        int ci = Math.min(n, m) / 2;

        for (int i = 0; i < ci; i++) {
            int parms = (2 * (n - 2 * i) + 2 * (m - 2 * i) - 4);
            int rotations = k % parms;
            for (int t = 0; t < rotations; t++) {
                rotation(i, n - 1 - i, i, m - 1 - i);
            }
        }

        prtints(maps, n, m);
    }
}

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

백준 마법사 상어와 토네이도  (0) 2024.04.02
백준 최소 회의실 개수  (0) 2024.04.02
백준 0 만들기  (1) 2024.04.01
백준 로봇 시뮬레이션  (1) 2024.04.01
백준 -탑  (0) 2024.03.30

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

 

7490번: 0 만들기

각 테스트 케이스에 대해 ASCII 순서에 따라 결과가 0이 되는 모든 수식을 출력한다. 각 테스트 케이스의 결과는 한 줄을 띄워 구분한다.

www.acmicpc.net

쉬운 문제이고 개인적으로 실버 1 정도 수준인듯하네요.

난이도는 골드5라고하는데 흠 쉽네요

import java.util.*;
import java.io.*;
public class Main {
	public static int A;
	public static int B;
	public static boolean bOkay=true;
	public static ArrayList<String> anws=new ArrayList<>();
	public static void Prints(){
		System.out.println();
		for(int i=0;i<B;i++){
			for(int j=0;j<A;j++){
				if(maps[i][j].bCheck==true){
					System.out.print(1+",");
				}else{
					System.out.print(0+",");
				}
			}
			System.out.println();
		}
		System.out.println();

	}
	public static class Robot{
		public int x;
		public int y;
		public int dir;
		public Robot(int x,int y, int dir){
			this.x=x;
			this.y=y;
			this.dir=dir;
		}
	}
	public static class RMaps{
		public int rnum;
		public boolean bCheck=false;
		public RMaps(int rnum, boolean bCheck){
			this.rnum=rnum;
			this.bCheck=bCheck;
		}
	}

	public static class TestCommand{
		public int r;
		public char command;
		public int loop;
		public TestCommand(int r,char command, int loop){
			this.r=r;
			this.command=command;
			this.loop=loop;
		}
	}

	public static void forword(int x, int y,int dir,int rnum){
		switch (dir){
			case 0:
				//n
				int checkY=y-1;
				if(checkY<0){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[checkY][x].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[checkY][x].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				robots.get(rnum).y=checkY;
				break;
			case 1:
				//w
				int checkX=x-1;
				if(checkX<0){
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[y][checkX].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[y][checkX].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).x=checkX;
				break;
			case 2:
				//s
				int checkY2=y+1;
				if(checkY2>=B){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[checkY2][x].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[checkY2][x].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).y=checkY2;
				break;
			case 3:
				int checkX2=x+1;
				if(checkX2>=A){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[y][checkX2].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[y][checkX2].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).x=checkX2;
				break;
			default:
				break;
		}
	}

	public static RMaps maps[][];
	public static ArrayList<Robot> robots=new ArrayList<>();
	public static ArrayList<TestCommand> testCommands=new ArrayList<>();
	public static void main(String[] args) throws Exception {
		Scanner scan= new Scanner(System.in);
		 A=scan.nextInt(); //5
		 B=scan.nextInt(); //4
		maps=new RMaps[B][A];//4 x 5
		int n=scan.nextInt();
		int m=scan.nextInt();

		for(int i=0;i<B;i++){//y 4
			for(int j=0;j<A;j++){//x 5
				maps[i][j]=new RMaps(-1,false);
			}
		}

		for(int i=0;i<n;i++){
			int x=scan.nextInt()-1; // 5
			int y=B-scan.nextInt();  // 4
			String dir=scan.next();
			int d=0;
			if(dir.charAt(0)=='N'){
				d=0;
			}else if(dir.charAt(0)=='W'){
				d=1;
			}
			else if(dir.charAt(0)=='S'){
				d=2;
			}
			else if(dir.charAt(0)=='E'){
				d=3;
			}
			robots.add(new Robot(x,y,d));
			maps[y][x].bCheck=true;
			maps[y][x].rnum=i;
		}
		//Prints();
		for(int i=0;i<m;i++){
			int r=scan.nextInt();
			String command=scan.next();
			int loop=scan.nextInt();
			testCommands.add(new TestCommand(r,command.charAt(0),loop));
		}


		for(int t=0;t<testCommands.size();t++){
				int rnum=testCommands.get(t).r-1;
				char commad=testCommands.get(t).command;
				int loop =testCommands.get(t).loop;


				int initx=robots.get(rnum).x;
				int inity=robots.get(rnum).y;

				bOkay=true;

				for(int i=0;i<loop;i++){
					int x=robots.get(rnum).x;
					int y=robots.get(rnum).y;
					int dir=robots.get(rnum).dir;
					switch(commad){
						case 'L':
							dir=dir+1;
							robots.get(rnum).dir=dir%4;
							break;
						case 'R':
							dir=dir-1;
							if(dir<0){
								dir=3;
							}
							robots.get(rnum).dir=dir%4;
							break;
						case 'F':
							forword(x,y,dir,rnum);
							if(bOkay==false){
								i=loop+1;
								continue;
							}
							break;
						default:
							break;
					}
				}

				if(bOkay==true){

					maps[inity][initx].bCheck=false;
					maps[inity][initx].rnum=-1;
					maps[robots.get(rnum).y][robots.get(rnum).x].rnum=rnum;
					maps[robots.get(rnum).y][robots.get(rnum).x].bCheck=true;
					//Prints();

					//System.out.println(robots.get(rnum).x+","+robots.get(rnum).y+","+robots.get(rnum).dir);
				}

			if(anws.size()>0){
				break;
			}
		}

		if(anws.size()>0){
			System.out.print(anws.get(0));
		}else{
			System.out.print("OK");
		}
	}
}

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

백준 최소 회의실 개수  (0) 2024.04.02
백준 배열돌리기2  (0) 2024.04.02
백준 로봇 시뮬레이션  (1) 2024.04.01
백준 -탑  (0) 2024.03.30
백준 배열돌리기4  (0) 2024.03.30

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

 

2174번: 로봇 시뮬레이션

첫째 줄에 두 정수 A, B가 주어진다. 다음 줄에는 두 정수 N, M이 주어진다. 다음 N개의 줄에는 각 로봇의 초기 위치(x, y좌표 순) 및 방향이 주어진다. 다음 M개의 줄에는 각 명령이 명령을 내리는 순

www.acmicpc.net

음 문제 자체는 어렵지 않았고

조금 헤맷던 부분이 문제를 잘못읽어서 시간이 걸렸던 문제입니다.

import java.util.*;
import java.io.*;
public class Main {
	public static int A;
	public static int B;
	public static boolean bOkay=true;
	public static ArrayList<String> anws=new ArrayList<>();
	public static void Prints(){
		System.out.println();
		for(int i=0;i<B;i++){
			for(int j=0;j<A;j++){
				if(maps[i][j].bCheck==true){
					System.out.print(1+",");
				}else{
					System.out.print(0+",");
				}
			}
			System.out.println();
		}
		System.out.println();

	}
	public static class Robot{
		public int x;
		public int y;
		public int dir;
		public Robot(int x,int y, int dir){
			this.x=x;
			this.y=y;
			this.dir=dir;
		}
	}
	public static class RMaps{
		public int rnum;
		public boolean bCheck=false;
		public RMaps(int rnum, boolean bCheck){
			this.rnum=rnum;
			this.bCheck=bCheck;
		}
	}

	public static class TestCommand{
		public int r;
		public char command;
		public int loop;
		public TestCommand(int r,char command, int loop){
			this.r=r;
			this.command=command;
			this.loop=loop;
		}
	}

	public static void forword(int x, int y,int dir,int rnum){
		switch (dir){
			case 0:
				//n
				int checkY=y-1;
				if(checkY<0){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[checkY][x].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[checkY][x].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				robots.get(rnum).y=checkY;
				break;
			case 1:
				//w
				int checkX=x-1;
				if(checkX<0){
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[y][checkX].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[y][checkX].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).x=checkX;
				break;
			case 2:
				//s
				int checkY2=y+1;
				if(checkY2>=B){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[checkY2][x].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[checkY2][x].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).y=checkY2;
				break;
			case 3:
				int checkX2=x+1;
				if(checkX2>=A){
					//wall
					int tmp=rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into the wall";
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}

				if(maps[y][checkX2].bCheck==true){
					//robot collision
					int tmp=rnum+1;
					int tmp2=maps[y][checkX2].rnum+1;
					String tmpAnw="Robot "+tmp+" crashes into robot "+tmp2;
					anws.add(tmpAnw);
					bOkay=false;
					break;
				}
				robots.get(rnum).x=checkX2;
				break;
			default:
				break;
		}
	}

	public static RMaps maps[][];
	public static ArrayList<Robot> robots=new ArrayList<>();
	public static ArrayList<TestCommand> testCommands=new ArrayList<>();
	public static void main(String[] args) throws Exception {
		Scanner scan= new Scanner(System.in);
		 A=scan.nextInt(); //5
		 B=scan.nextInt(); //4
		maps=new RMaps[B][A];//4 x 5
		int n=scan.nextInt();
		int m=scan.nextInt();

		for(int i=0;i<B;i++){//y 4
			for(int j=0;j<A;j++){//x 5
				maps[i][j]=new RMaps(-1,false);
			}
		}

		for(int i=0;i<n;i++){
			int x=scan.nextInt()-1; // 5
			int y=B-scan.nextInt();  // 4
			String dir=scan.next();
			int d=0;
			if(dir.charAt(0)=='N'){
				d=0;
			}else if(dir.charAt(0)=='W'){
				d=1;
			}
			else if(dir.charAt(0)=='S'){
				d=2;
			}
			else if(dir.charAt(0)=='E'){
				d=3;
			}
			robots.add(new Robot(x,y,d));
			maps[y][x].bCheck=true;
			maps[y][x].rnum=i;
		}
		//Prints();
		for(int i=0;i<m;i++){
			int r=scan.nextInt();
			String command=scan.next();
			int loop=scan.nextInt();
			testCommands.add(new TestCommand(r,command.charAt(0),loop));
		}


		for(int t=0;t<testCommands.size();t++){
				int rnum=testCommands.get(t).r-1;
				char commad=testCommands.get(t).command;
				int loop =testCommands.get(t).loop;


				int initx=robots.get(rnum).x;
				int inity=robots.get(rnum).y;

				bOkay=true;

				for(int i=0;i<loop;i++){
					int x=robots.get(rnum).x;
					int y=robots.get(rnum).y;
					int dir=robots.get(rnum).dir;
					switch(commad){
						case 'L':
							dir=dir+1;
							robots.get(rnum).dir=dir%4;
							break;
						case 'R':
							dir=dir-1;
							if(dir<0){
								dir=3;
							}
							robots.get(rnum).dir=dir%4;
							break;
						case 'F':
							forword(x,y,dir,rnum);
							if(bOkay==false){
								i=loop+1;
								continue;
							}
							break;
						default:
							break;
					}
				}

				if(bOkay==true){

					maps[inity][initx].bCheck=false;
					maps[inity][initx].rnum=-1;
					maps[robots.get(rnum).y][robots.get(rnum).x].rnum=rnum;
					maps[robots.get(rnum).y][robots.get(rnum).x].bCheck=true;
					//Prints();

					//System.out.println(robots.get(rnum).x+","+robots.get(rnum).y+","+robots.get(rnum).dir);
				}

			if(anws.size()>0){
				break;
			}
		}

		if(anws.size()>0){
			System.out.print(anws.get(0));
		}else{
			System.out.print("OK");
		}
	}
}

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

백준 배열돌리기2  (0) 2024.04.02
백준 0 만들기  (1) 2024.04.01
백준 -탑  (0) 2024.03.30
백준 배열돌리기4  (0) 2024.03.30
백준-배열돌리기3  (1) 2024.03.25

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

 

2493번: 탑

첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1

www.acmicpc.net

흠 아무리 봐도 스택 문제보단 그리드 문제같은 문제 ... ㅎㅎ ;; 

시간 복잡도랑 메모리 초과 문제가 발생할수 있습니다.

시간 복잡도는 O(N^2)를 회피해야합니다.

최대한 O(N) 가깝게 for  문을 돌려야 하네요. ㅎㅎ 

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

public class Main {
	public static class Tower{
		public long tower;
		public long index;
		public Tower(long tower,long index) {
			this.tower=tower;
			this.index=index;
		}
	}
	public static void main(String[] args) throws Exception {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int n=Integer.parseInt(bf.readLine());
		
		long tower[]=new long[n];
		long send[]=new long[n];
		
		StringTokenizer stmp=new StringTokenizer(bf.readLine()," ");
		Stack<Tower> stacks=new Stack<>();
		for(int i=0 ;i<n;i++) {
			tower[i] = Long.parseLong(stmp.nextToken());
			while(!stacks.isEmpty()) {
				if(tower[i]>stacks.peek().tower) {
					stacks.pop();
				}else {
					System.out.print(stacks.peek().index+" ");
					break;
				}
			}
			//9 5 7
			if(stacks.empty()){
	            System.out.print(0 + " ");
	        }
			stacks.push( new Tower (tower[i], i+1 ));
		}
		
		
	}
}

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

백준 0 만들기  (1) 2024.04.01
백준 로봇 시뮬레이션  (1) 2024.04.01
백준 배열돌리기4  (0) 2024.03.30
백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 파이어볼  (0) 2024.03.03

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

 

17406번: 배열 돌리기 4

크기가 N×M 크기인 배열 A가 있을때, 배열 A의 값은 각 행에 있는 모든 수의 합 중 최솟값을 의미한다. 배열 A가 아래와 같은 경우 1행의 합은 6, 2행의 합은 4, 3행의 합은 15이다. 따라서, 배열 A의

www.acmicpc.net

어.. 생각보다 좀 시간이 걸렸던 문제고요. 한 3일정도 걸렸습니다.

첫번째는 문제를 잘못읽어서 틀렸었고요.

두번째는 회전시킬때 너무  array 이중루프문안에서 해결하려고 해서 문제가 발생했습니다.

그냥 쉽게 탑 , 바텀, 왼쪽, 오른쪽으로 천천히 시계방향으로 회전시킨다고 생각하면 쉽게 풀립니다.

임의의 숫자는 백트래킹으로 순서를 정해주면 됩니다.

import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
		public static int initmaps[][];
	public static int maps[][];
	public static int copymaps[][];
	public static boolean bCheck[];
	public static int n;
	public static int m;
	public static int k;
	public static int mins =0;
	public static  ArrayList<TestCommand>testCommands=new ArrayList<>();
	public static  ArrayList<TestCommand>testSaveCommands=new ArrayList<>();
	public static  class TestCommand{
		public int r;
		public int c;
		public int s;

		public TestCommand(int r, int c, int s){
			this.r=r;
			this.c=c;
			this.s=s;
		}
	}
	public static void prtints(int maps[][],int n, int m){
		System.out.println("");
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				System.out.print(maps[i][j]+",");
			}
			System.out.println("");
		}
	}

	public static void rotation(int startr,int endr,int startc ,int endc){
		//top
		for(int i=startc; i < endc ;i++){
			copymaps[startr][i+1] =maps[startr][i];
		}

		//left
		for(int i=startr+1; i<=endr ;i++){
			copymaps[i-1][startc] =maps[i][startc];
		}

		//right
		for(int i=startr; i<endr ;i++){
			copymaps[i+1][endc] =maps[i][endc];
		}

		//bottom
		for(int i=startc+1 ; i<=endc ; i++){
			copymaps[endr][i-1] =maps[endr][i];
		}
	}

	public static void gRotation(int mr,int mc, int ms){
		//make range

		int startR = mr - ms - 1;
		int endR   = mr + ms - 1;
		int startC = mc - ms - 1;
		int endC   = mc + ms - 1;

		//rotation
		for(int i=0;i<ms;i++){
			rotation(startR+i,endR-i,startC+i,endC-i);
		}

		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				int tmp=copymaps[i][j];
				maps[i][j]=tmp;
			}
		}
	}

	public static void backtracking(int cnt){
		if(cnt>=k){
			//prtints(maps,n,m);
			for(int i=0;i<testSaveCommands.size();i++){
				//System.out.println("r"+testSaveCommands.get(i).r);
				gRotation(testSaveCommands.get(i).r,testSaveCommands.get(i).c, testSaveCommands.get(i).s);
			}

			//prtints(maps,n,m);
			//System.out.println("");

			for(int i=0;i<n;i++){
				int sum=0;
				for(int j=0;j<m;j++){
					sum+=maps[i][j];
				}
				if(sum<=mins||mins==0){
					mins=sum;
				}
			}

			for(int i=0;i<n;i++){
				for(int j=0;j<m;j++){
					int tmp =initmaps[i][j];
					maps[i][j]=tmp;
					copymaps[i][j]=tmp;
				}
			}
		}

		for(int i=0;i<k;i++){
			if(bCheck[ i ]==false){
				bCheck[ i ]=true;
				testSaveCommands.add( testCommands.get( i ) );
				backtracking(cnt+1 );
				testSaveCommands.remove( testSaveCommands.size()-1);
				bCheck[ i ]=false;
			}
		}
	}
	public static void main(String[] args) throws Exception {
		Scanner scan= new Scanner(System.in);
		n=scan.nextInt();
		m=scan.nextInt();
		k=scan.nextInt();
		maps=new int[n][m];
		initmaps=new int[n][m];
		copymaps=new int[n][m];
		bCheck=new boolean[k];
		//make map
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				int tmp =scan.nextInt();
				maps[i][j]=tmp;
				copymaps[i][j]=tmp;
				initmaps[i][j]=tmp;
			}
		}

		for(int z=0;z<k;z++) {
			int r = scan.nextInt();
			int c = scan.nextInt();
			int s = scan.nextInt();
			testCommands.add(new TestCommand(r,c,s));
		}

		//backtracking
		for(int i=0;i<testCommands.size();i++){
			if(bCheck[i]==false) {
				bCheck[i] = true;
				testSaveCommands.add(testCommands.get(i));//341
				backtracking(1 );
				testSaveCommands.remove(testSaveCommands.size()-1);
				//testSaveCommands.remove(testCommands.size()-i);
				bCheck[i] = false;
			}
		}
		System.out.print(mins);
	}
}

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

백준 로봇 시뮬레이션  (1) 2024.04.01
백준 -탑  (0) 2024.03.30
백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 - 마법사 상어와 비바라기  (1) 2024.02.24

+ Recent posts