반응형

import java.util.Scanner;

public class BaekjoonAlgo_2675 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		
		int tc = sc.nextInt();
		String[] result = new String[tc];
		
		for(int i=0;i<tc;i++) {
			result[i] ="";
			int r = sc.nextInt();
			String s = sc.next();
			
			char[] arr = s.toCharArray();
			
			for(int j=0;j<arr.length;j++) {
				for(int k=0;k<r;k++) {
					result[i] += arr[j];					
				}
			}
		}
		
		for(int i=0;i<tc;i++) {
			System.out.println(result[i]);
		}
	}

}

 

 

반응형

'알고리즘 > Baekjoon' 카테고리의 다른 글

[Baekjoon] #1152 단어의 개수  (0) 2022.03.07
[Baekjoon] #1157 단어 공부  (0) 2022.03.06
[Baekjoon] #2606 바이러스  (0) 2020.09.02
[Baekjoon] #3184 양  (0) 2020.04.28
[ Baekjoon ] #2178 미로 탐색  (0) 2020.04.26
반응형

[풀이] BFS로 접근 > 바이러스가 퍼지는 PC를 Queue에 담고 Queue에서 연결된 PC 개수 조회

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Baekjoon2606 {

	static int pc;
	static int network;
	static int[][] map;
	static int[] visit;
	static int cnt =0;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner sc = new Scanner(System.in);
		
		pc = 0 ;
		network = 0;
		
		pc = sc.nextInt();
		network = sc.nextInt();
		map = new int[pc+1][pc+1];
		visit = new int[pc+1];
		
		for(int i=0;i<network;i++) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			
			map[n][m] = 1;
			map[m][n] = 1;
		}		
		
		virusMove();
		System.out.println(cnt-1); // 1번 컴퓨터를 제외 한 수
		
	}
	
	public static void virusMove() {
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(1);
		
		while(!queue.isEmpty()) {
			int startPc = queue.poll();
			
			for(int i=1;i<=pc;i++) {
				if(map[startPc][i] == 1 && visit[i] != 1) {
					// 방문하지 않은 연결된 PC 시작점 Queue에 추가
					queue.add(i);
					visit[i] = 1;
					cnt++;
				}
			}
		}
	}
}

[Github] github.com/blackmount22/Algorithm/blob/master/Baekjoon2606.java

[Baekjoon] www.acmicpc.net/problem/2606

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어��

www.acmicpc.net

 

반응형

'알고리즘 > Baekjoon' 카테고리의 다른 글

[Baekjoon] #1157 단어 공부  (0) 2022.03.06
[Baekjoon] #2675 문자열 반복  (0) 2022.03.05
[Baekjoon] #3184 양  (0) 2020.04.28
[ Baekjoon ] #2178 미로 탐색  (0) 2020.04.26
[ Baekjoon ] #7576 토마토  (0) 2020.04.22
반응형

프로그래머스: 2016년 문제

https://programmers.co.kr/learn/courses/30/lessons/12901

 

풀이 방식:

입력받은 a월 b일과 1월 1일 금요일을 기준으로 날짜수의 차이를 구한 후, 7로 나눈 다음 나머지 값으로 days[] 배열에서 해당 요일 조회

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

class Solution {
    public String solution(int a, int b) {
        String answer = "";
        String date1 = "2016-01-01";
		String date2 = "2016-"+a+"-"+b;
		String[] days = {"FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"};
		
		try {			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date firstDate = format.parse(date1);
			Date secondDate = format.parse(date2);
			
			long timeDiff = secondDate.getTime() - firstDate.getTime();
			long calTimeDiff = timeDiff / (24*60*60*1000);
			
			int remainder = (int)calTimeDiff % 7;
			
			answer = days[remainder];
			
		}catch(ParseException e){
			
		}
        
        return answer;
    }
}

 

[Github]

https://github.com/blackmount22/algorithm-programmers/blob/master/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4%20-%202016.txt

반응형

'알고리즘 > 프로그래머스' 카테고리의 다른 글

숫자 짝꿍  (0) 2024.02.25
실패율  (0) 2024.02.23
추억 점수  (0) 2024.02.22
푸드 파이트 대회  (0) 2024.02.21
모의고사  (0) 2020.08.01
반응형

완전 탐색(Brute-Force)

: 컴퓨터의 빠른 계산 능력을 이용하여 모든 경우의 수를 전부 탐색하는 방법으로, 탐색하는 방식에 따라

Brute-Force(for문, if문을 이용하여 처음부터 끝까지 탐색하는 방법), DFS/BFS 그래프 알고리즘, 백트래킹 등이 있다.

단점으로는 완전탐색이다 보니 답을 찾는데 시간이 오래 걸린다.

 

프로그래머스: 모의고사 문제

https://programmers.co.kr/learn/courses/30/lessons/42840

import java.util.ArrayList;
import java.util.Collections;

class Solution {
    public int[] solution(int[] answers) {
		int[] studentA = {1,2,3,4,5};
		int[] studentB = {2,1,2,3,2,4,2,5};
		int[] studentC = {3,3,1,1,2,2,4,4,5,5};
		int[] result;
		
		int answerA = 0;
		int answerB = 0;
		int answerC = 0;
		
		for(int i=0;i<answers.length;i++) {
			if(studentA[i%studentA.length] == answers[i]) answerA++;
			if(studentB[i%studentB.length] == answers[i]) answerB++;
			if(studentC[i%studentC.length] == answers[i]) answerC++;
		}
		
		int maxCnt = Math.max(Math.max(answerA, answerB), answerC);
		ArrayList<Integer> ar = new ArrayList<Integer>();
		
		if(maxCnt == answerA) {
			ar.add(1);
		}
		
		if(maxCnt == answerB) {
			ar.add(2);
		}
		
		if(maxCnt == answerC) {
			ar.add(3);
		}
		
		Collections.sort(ar);
		result = new int[ar.size()];
		for(int i=0;i < ar.size();i++) {
			result[i] = ar.get(i);
		}
        
        return result;
    }
}

 

반응형

'알고리즘 > 프로그래머스' 카테고리의 다른 글

숫자 짝꿍  (0) 2024.02.25
실패율  (0) 2024.02.23
추억 점수  (0) 2024.02.22
푸드 파이트 대회  (0) 2024.02.21
2016년  (0) 2020.08.31
반응형

[Baekjoon][https://www.acmicpc.net/problem/3184]

 

각 울타리 안에 있는 늑대와 양의 개수를 구하고 비교하는 문제로

너비 우선 탐색(BFS) 알고리즘 적용

 

미키의 뒷마당에서 울타리가 아니고(map[r][c] != ’#’) && 방문하지 않은(visit[r][c] != 0) 영역 일 때 BFS 알고리즘을 호출한다.

현재 위치를 Queue 값에 넣은 후 Queue 값이 존재 할 경우 상, 하, 좌, 우 방향으로 이동하면서

울타리 안에 있는 영역의 늑대와, 양의 수를 구한다.

 

수직, 수평으로 이동하면서 울타리 안 영역을 모두 BFS로 탐색 시,

늑대와 양의 수를 구한 후 늑대가 존재하면 전체 늑대 수에 남은 늑대 수를 더해주고,

양이 존재하면 전체 야 수에 남은 양 수를 더해준다.

 

이렇게 울타리 안 모든 영역을 BFS로 한 번씩 탐색 후 전체 개수를 출력한다.

 

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Location3184{
	int x;
	int y;
	
	public Location3184(int x, int y) {
		// TODO Auto-generated constructor stub
		this.x = x;
		this.y = y;
	}
}

// Queue에 들어갈 기준점이 필요

public class Main {

	static int r;
	static int c;
	static char map[][];
	static int visit[][];
	static Queue<Location3184> location;
	static int total_sheep =0;
	static int total_wolf = 0;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		
		r = sc.nextInt();
		c = sc.nextInt();
		
		map = new char[r][c];
		visit = new int[r][c];
		location = new LinkedList<>();
		
		for(int i=0;i<r;i++) {
			String str = sc.next();
			for(int j=0;j<c;j++) {
				map[i][j] = str.charAt(j);
			}
		}
		

		for(int i=0;i<r;i++) {
			for(int j=0;j<c;j++) {
				if(map[i][j] != '#' && visit[i][j] == 0) {
					getBFS(i, j);
				}
			}
		}
		
		
		System.out.println(total_sheep+" "+total_wolf); 
	}
	
	public static void getBFS(int i, int j) {
		int[] xx = {-1, 0, 1, 0};
		int[] yy = {0, 1, 0, -1};
		
		int curSheep = 0;
		int curWolf = 0;
		visit[i][j] = 1;
		location.offer(new Location3184(i, j));
		
		if(map[i][j] == 'o') {
			curSheep++;
		} else if(map[i][j] == 'v') {
			curWolf++;
		}
		
		while(!location.isEmpty()) {
			int x = location.peek().x;
			int y = location.poll().y;

			for(int k=0;k<4;k++) {
				int ax = x+xx[k];
				int ay = y+yy[k];
				
				if(ax>=0 && ay>=0 && ax<r && ay<c) {
					if(visit[ax][ay] == 0 && map[ax][ay] == 'o') {
						curSheep++;
					} else if( visit[ax][ay] == 0 && map[ax][ay] == 'v') {
						curWolf++;
					}
					
					if(visit[ax][ay] == 0 && map[ax][ay] != '#') {
						location.offer(new Location3184(ax, ay));
						visit[ax][ay] = 1;
					}
				}
			}
		}

		if(curWolf>=curSheep) {
			total_wolf += curWolf;
		} else if(curSheep > curWolf) {
			total_sheep += curSheep;
		}
	}
}
반응형

'알고리즘 > Baekjoon' 카테고리의 다른 글

[Baekjoon] #2675 문자열 반복  (0) 2022.03.05
[Baekjoon] #2606 바이러스  (0) 2020.09.02
[ Baekjoon ] #2178 미로 탐색  (0) 2020.04.26
[ Baekjoon ] #7576 토마토  (0) 2020.04.22
[ Baekjoon ] #5427 불  (0) 2020.04.20

+ Recent posts