Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

정유경 / 10월 4주차 / 월 #296

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

youkyoungJung
Copy link
Contributor


🎈boj 12919 - A와 B2


🗨 해결방법 :


S -> T 가 아닌 T-> S가 되는 방법을 생각하여 풀었습니다.

📝메모 :


S -> T 가 되는 경우로 생각하여 문제를 풀면 시간초과 난다.

✔코드 :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	private static String t;
	private static String sb;
	static boolean flag = false;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		sb = br.readLine();
		t = br.readLine();
		
		solved(t);
		System.out.println((flag)?1:0);
		
	}//end main

	private static void solved(String t) { //t->s
		StringBuilder answer = new StringBuilder();
		answer.append(t);
		
		//기저조건
		if(answer.toString().equals(sb.toString())) {
			flag = true;
			return;
		}
		
		if(answer.length() <= sb.length()) {
			return;
		}
		
		//문자열 맨앞에 B가 있으면 B를 삭제할 수 있음 BAB -> BA, BA -> A
		//맨앞에 B가 있으면 reverse() 후 맨뒤 B 삭제
		if(answer.charAt(0) == 'B') {
			StringBuilder sub = new StringBuilder();
			sub.append(answer);
			sub.reverse();
			solved(sub.substring(0,sub.length()-1));
		}
		
		//문자열의 맨 뒤에 A가 있으면 A를 삭제할 수 있음
		if(answer.charAt(answer.length()-1) == 'A') {
			StringBuilder sub = new StringBuilder();
			sub.append(answer);
			solved(sub.substring(0, sub.length()-1));
		}		
		
	}

}//end class


🎈boj 10159 - 저울


🗨 해결방법 :


bfs를 통해 부모노드수 + 자식노드의수 + 자신의 수를 구하여 해결하였다.

📝메모 :


✔코드 :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main_10159저울 {

	private static int[][] matrix;
	private static int n;

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		n = Integer.parseInt(br.readLine()); // 물건의 개수
		int m = Integer.parseInt(br.readLine()); // 미리 측정된 물건 쌍의 개수

		matrix = new int[n + 1][n + 1];

		for (int i = 0; i < m; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine(), " ");
			int m1 = Integer.parseInt(st.nextToken()); // 물건1
			int m2 = Integer.parseInt(st.nextToken()); // 물건2

			matrix[m1][m2] = 1; // 간선 표시
		}
		
		for (int i = 1; i < matrix.length; i++) {
			int res = answer(i);
			sb.append(n-res).append("\n");
		}
		System.out.println(sb.toString());
		
		

	}// end main

	private static int answer(int k) {
		int child = 0;
		boolean[] isVisited = new boolean[n+1];
		//자식코드 
		Queue<Integer> queue = new ArrayDeque<Integer>();
		queue.offer(k); //시작점은 1
		
		while(!queue.isEmpty()) {
			int current = queue.poll();
			
			for (int i = 1; i < matrix.length; i++) {
				if(!isVisited[i] && matrix[current][i] == 1) { //자식코드면
					queue.offer(i); //자식 들어감
					isVisited[i] = true;
					child++;
				}
			}
		}
		
		//부모
		int parent = 0;
		boolean[] isVisited2 = new boolean[n+1];
		//자식코드 
		Queue<Integer> queue2 = new ArrayDeque<Integer>();
		queue2.offer(k); //시작점은 1
		
		while(!queue2.isEmpty()) {
			int current = queue2.poll();
			
			for (int i = 1; i < matrix.length; i++) {
				if(!isVisited2[i] && matrix[i][current] == 1) { //자식코드면
					queue2.offer(i); //자식 들어감
					isVisited2[i] = true;
					parent++;
				}
			}
		}
		
//		System.out.println("child: "+child +", parent: "+parent);
		return (child + parent + 1);
		
	}

}// end class

@youkyoungJung youkyoungJung changed the title 10월 4주차 / 월 / 정유경 정유경 / 10월 4주차 / 월 Oct 23, 2023
Copy link
Contributor

@dpwns523 dpwns523 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다.!


}// end main

private static int answer(int k) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

부모, 자식을 카운팅하는 코드가 거의 일치하는데 answer이라는 메서드 두 번 호출로 각각의 값을 반환시켜서 처리하는건 어떨까요?

answer.append(t);

//기저조건
if(answer.toString().equals(sb.toString())) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

t.equals로 스트링 비교 처리가 깔끔할 거 같은데
혹시 StringBuilder를 쓰시는 이유가 있나요?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

모든 경우에 equals를 사용해서 equals 비용이 무조건 O(n)이라고 생각해서 문제가 되지 않을까 했는데 자바7부터 길이가 다르면 false를 리턴하는 빠른 처리가 생겼었다네요..

하나 알아갑니다^^

@IntrinsicCandidate
    public static boolean equals(byte[] value, byte[] other) {
        if (value.length == other.length) {
            for (int i = 0; i < value.length; i++) {
                if (value[i] != other[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

Copy link
Member

@leetaggg leetaggg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

유경님 요즘 폼이 장난이 아니시네요! 고생하셨어요~~❤❤

@youkyoungJung
Copy link
Contributor Author

태호님 감사드립니다! 함께 힘내서 알고리즘 뿌셔보아요!

@DeveloperYard
Copy link
Member

항상 좋은 코드 잘 구경하고 가요! 예준님이 발견하신 것처럼 길이 비교를 통해 boolean 값을 리턴하는 구문은 처음 보네요.
감사합니다!!! 좋은 하루 되세요 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants