Giter VIP home page Giter VIP logo

acmicpc_note's People

Contributors

gmldusdkwk avatar jaymerem avatar soyoung210 avatar

Watchers

 avatar  avatar  avatar  avatar

acmicpc_note's Issues

B_2504 리뷰반영 하기.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Stack;

public class Main {
    static Stack<String> s = new Stack<>();

    public static void main(String[] args) {

    }

    /*
        현재 알고리즘 : 닫힌 괄호 쌍의 갯수만큼 수로 계산하여 마지막에 더하는 방식인듯.
        [()]() ==> stack <6,2>

        stack 상태
        stack <[(>
        stack <[2>
        stack <6>
        stack <6(>
        stack <6,2>

        하나의 스택만 사용하려고 해서 조금 어렵게 짠 듯한 느낌.

        *** 알고리즘 자체는 참신 ㅋㅋ ***

        결론 : 크게 바꿀거 없음. 잘 짬. 다만 로직이 어려움.
     */
    private static void originalMain() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            char[] chArr = br.readLine().toCharArray();
            int chLeng = chArr.length;
            if (chLeng % 2 != 0) {
                System.out.println("0");
                return;
            }
            int i;

            int answer = 0;

            for (i = 0; i < chLeng; i++) {
                //stackOp call
                if (chArr[i] == ')') {
                    stackOp(2, ')');
                } else if (chArr[i] == ']') {
                    stackOp(3, ']');
                } else {
                    s.push(Character.toString(chArr[i]));
                }
            }

            while (!s.isEmpty()) {
                if (isInteger(s.peek())) {
                    answer += Integer.parseInt(s.pop());
                } else {
                    System.out.println("0");
                    return;
                }
            }
            System.out.println(answer);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    /*
        try - catch의 상태가??? --> 왜 쓴진 알거 같은데.. 하나로 합치는게

        강제종료가 상당히 많이 들어간다.
        stackOp의 동작을 호출하는 부분으 메인에서만 있다면 boolean 값으로 반환해도 좋을듯 싶음.

        exit(0)을 잘 안쓰는 이유 : 종료 시점을 알기 힘들어짐.

        ')' or ']'만 있는 케이스의 경우 문자열 길이만큼 실행됨. (try-catch에 걸리기 때문에 어떠한 동작도 실행되지는 않으나, 반복문이 살아있음.)

        반복문을 사용하면 코드는 간결해지지만, 현재 짠 방식으로 할 때 코드의 이해가 조금 더 쉽다는 장점이 있음.
     */
    public static void stackOp(int op, char bracket) {
        int sum = 0;
        String tmp;
        String tmp2;
        String second;

        try {
            tmp = s.pop();
            //System.out.println("tmp : "+tmp);
            if (isInteger(tmp)) {
                sum += Integer.parseInt(tmp);
                try {
                    second = s.peek();
                    if (isInteger(second)) {
                        tmp2 = s.peek();
                        while (isInteger(tmp2)) {
                            s.pop();
                            sum += Integer.parseInt(tmp2);
                            tmp2 = s.peek();
                        }
                        s.pop();
                        s.push(Integer.toString(sum * op));
                    } else {
                        if (bracket == ')') {
                            if (s.pop().charAt(0) == '(') {
                                s.push(Integer.toString(Integer.parseInt(tmp) * op));
                            } else {
                                System.out.println("0");
                                System.exit(0);
                            }
                        } else {
                            if (s.pop().charAt(0) == '[') {
                                s.push(Integer.toString(Integer.parseInt(tmp) * op));
                            } else {
                                System.out.println("0");
                                System.exit(0);
                            }
                        }

                    }

                } catch (Exception e) {
                    //System.out.println("0"); return;
                }
            } else {
                if (bracket == ')') {
                    if (tmp.charAt(0) == '(') {
                        s.push("2");
                    } else {
                        System.out.println("0");
                        System.exit(0);
                    }
                } else {
                    if (tmp.charAt(0) == '[') {
                        s.push("3");
                    } else {
                        System.out.println("0");
                        System.exit(0);
                    }
                }
                //s.push( (bracket=='(') ? '2' : '3' );
            }
        } catch (EmptyStackException ex) {
            //System.out.println("0"); return;
        }
    }


    /*
        기존 알고리즘 유지하며 바꾸고 싶은 부분 바꿔봄.
        정답임을 보장하진 않음. (안돌려봄)
     */

    private static char[] open = {'(', '['};
    private static char[] close = {')', ']'};

    private static void change() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            char[] chArr = br.readLine().toCharArray();
            int chLeng = chArr.length;
            if (chLeng % 2 != 0) {
                System.out.println("0");
                return;
            }
            int i;

            int answer = 0;

            boolean isOk = true;
            for (i = 0; i < chLeng; i++) {
                //stackOp call
                char c = chArr[i];
                for (int j = 0; j < 2; j++) {
                    if (c == close[j]) {
                        isOk = stackOpChange(j + 2, close[j]);
                        break;
                    }
                    if (c == open[j]) {
                        s.push(String.valueOf(c));
                        break;
                    }
                }
                if (!isOk) {
                    System.out.println(0);
                    return;
                }
            }

            while (!s.isEmpty()) {
                if (isInteger(s.peek())) {
                    answer += Integer.parseInt(s.pop());
                } else {
                    System.out.println("0");
                    return;
                }
            }
            System.out.println(answer);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static boolean stackOpChange(int op, char bracket) {

        // 닫힘 괄호만 있을 때 체크
        if (s.isEmpty()) {
            return false;
        }

        int sum = 0;
        String tmp;
        String second;

        tmp = s.pop();

        boolean isCheck = true;
        if (isInteger(tmp)) {
            sum += Integer.parseInt(tmp);
            second = s.peek();
            if (isInteger(second)) {
                while (isInteger(second)) {
                    s.pop();
                    sum += Integer.parseInt(second);
                    second = s.peek();
                }
                s.pop();
                s.push(Integer.toString(sum * op));
            } else {
                isCheck = isPush(
                        bracket,
                        String.valueOf(Integer.parseInt(tmp) * op),
                        s.pop().charAt(0)
                );
            }
        } else {
            isCheck = isPush(bracket, "", tmp.charAt(0));
        }
        return isCheck;
    }

    private static boolean isPush(char bracket, String value, char openC) {
        for (int i = 0; i < 2; i++) {
            if (bracket == close[i]) {
                if (openC == open[i]) {
                    if (value.length() == 0) {
                        s.push(String.valueOf(i + 2));
                    } else {
                        s.push(value);
                    }
                    break;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    /*
        이 방법은 되게 참신하네 ㅋㅋㅋㅋㅋㅋ
        catch만 하나로 합침
     */
    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException | NullPointerException e) {
            return false;
        }
        // only got here if we didn't return false
        return true;
    }
}

# 1865 웜홀문제

testcase 개수가 2개이나 for 문이 한번만 실행되는 문제.

//test = 2 
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
	int test = Integer.parseInt(br.readLine());
	String[] answer = new String[test];
	int i;
			
	for(i=0;i<test;i++) {
		System.out.println("===test===");
		String[] nmw = br.readLine().split(" ");
				
		int n = Integer.parseInt(nmw[0]); //3
		int m = Integer.parseInt(nmw[1]); //3
		int w = Integer.parseInt(nmw[2]); //1
		int[] dist = new int[n+1];
		Arrays.fill(dist,INF);
		// 2 3 4

		for (i = 1; i <= m; i++) { 
			String[] set = br.readLine().split(" ");
			
			int s1 = Integer.parseInt(set[0]);
			int e1 = Integer.parseInt(set[1]);
			int t1 = Integer.parseInt(set[2]);

			g.add(new Edge(s1,e1,t1));
			g.add(new Edge(e1,s1,t1));
		} 
		for (i = 1; i <= w; i++) { 
			String[] set2 = br.readLine().split(" ");

			int s2 = Integer.parseInt(set2[0]);
			int e2 = Integer.parseInt(set2[1]);
			int t2 = Integer.parseInt(set2[2]);	
			g.add(new Edge(s2,e2,t2*(-1)));	
		}				
				
		boolean minus = BellmanFord(dist,g,n,(m+w),1);
		System.out.println( (minus) ? "YES" : "NO" );
		g.clear();
		}
		System.out.println("===out===");
}catch(IOException ex) {
		System.out.println("===error===");
		ex.printStackTrace();
}

===test=== 는 한번만 출력되고, 바로 ===out=== 을 출력한다.

규칙

  1. Practice 를 default Branch로 사용
  2. feedback/issuenum_site_problemnum 로 사용.

한 주에 푸는 문제가 여러개 이므로... 실제 GitFlow 100% 매칭시키기엔 무리가 있음

# 여러가지 경험들 정리

PQ compareTo

//오름차순 정렬. 내림차순 하고싶으면 부등호만 바꾸자. 
	@Override
	public int compareTo(Element o){
		if(this.dist<o.dist) {
			return -1;
		}else if(this.dist > o.dist) {
			return 1;
		}else {
			return 0;
		}
    }

LowerBound

1965번.

PQ 사용 오류

39 38 9 35 39 20

--> 출력 : 39, 20, 35, 38, 9
PriorityQueue 의 정렬 방식을 Collections.reverseOrder() 로 조정.
잘못된 결과

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

public class B_9237 {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int count = Integer.parseInt(br.readLine());
		PriorityQueue<Integer> tree = new PriorityQueue<>(count, Collections.reverseOrder());
		StringTokenizer st = new StringTokenizer(br.readLine());

		int i;
		
		for(i=0;i<count;i++) {
			tree.add(Integer.parseInt(st.nextToken()));
		}
		int max = 0;
		System.out.println("max"+max);
		i = 1;
		for(Integer tmp : tree) {
			System.out.println("tmp"+tmp);
			max = (max < tmp) ? tmp : max;
		}
		System.out.println(max);
	}
}

Foolish mistakes

Owner어이없는 실수 모음집이다.
실수를 반복하지 않기 위한 log

  1. character는 한글자 이다.
int num = 11;
char ch = Character.forDigit(num,10);
//forDigit(숫자,진법) method.
  1. 반복문은 해당 인덱스로 돌자
for(List<Integer> an : result) {
      System.out.println("size : "+an.size());
       for(int k=0; k<4; k++) {
        	System.out.println(an.get(k));	
        }
       System.out.println("==============");
}

for에서 k를 쓰고 있지만 출력은 i로 하고선 java를 탓했다. 오류라고 생각했다.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.