www.acmicpc.net/problem/1967

 

1967번: 트리의 지름

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연

www.acmicpc.net

 

 

1. 루트로부터 가중치를 구한다.

2. 가중치 값이 들어있는 result 배열에서 최대 값 찾기

3. 최대 값을 가진 노드로부터 각 노드까지의 거리(지름)을 구하여 result 배열에 넣는다.

4. 그 배열에서 가장 큰 값이 최장 지름!

 

 주의점
- 루트에서 루트, index에서 index일때는 0으로 초기화 시켜준다. 
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)

N = int(input())
graph = [[] for _ in range(N+1)]
result = [0 for _ in range(N+1)]

max = 0

for i in range(N-1):
    a,b,c = map(int, input().split())
    graph[a].append([b,c])
    graph[b].append([a,c])

def bfs(i, graph, result):
    q = deque()
    for j in range(len(graph[i])):
        q.append(graph[i][j])
    while q:
        a,b = q.popleft()
        if result[a] == 0:
            result[a] = result[i] + b
            bfs(a, graph, result)

bfs(1, graph, result)
result[1] = 0

index = 0
tmp_max = 0
for i in range(len(result)):
    if tmp_max < result[i]:
        tmp_max = result[i]
        index = i

result = [0 for _ in range(N+1)]
bfs(index, graph, result)
result[index] = 0

tmp_max = 0
for i in range(len(result)):
    if tmp_max < result[i]:
        tmp_max = result[i]

print(tmp_max)

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

[백준] 1168번 요세푸스 문제 2 파이썬  (0) 2021.03.23
[백준]1107번 리모컨 파이썬  (0) 2021.02.23

1. 초급기

2. 실전기

3. 정체기

4. 고인물

 

1. 초급기

1) 기본서 : 해커스/위포트 (같이 공부하기) -> 자신과 비슷한 수준의 스터디원 구하는 것 추천

2) 문제를 봤을 때 모듈/피셋/피듈 파악할 수 있게끔 공부하기

3) 기본서에 충실하기

4) 인강 혹은 유튜브 강의 찾아보기

5) 전공 공부는 기사 필기 병행하기 ( 일주일에 10시간 추천)

 

2. 실전기

1) 실제 공기업 시험을 최대한 많이 쳐보기 -> 가장 좋은 모의고사다

2) 시중에 나오는 봉투 모의고사 풀기 : 시대고시/위포트/에듀윌/해커스/렛유인

 

3. 정체기

1) 실전경험 있는 사람과 스터디 하기

2) 신헌/하주응 PSAT for NCS 풀기

3) 에듀윌 

 

4. 고인물

1) 양치기 !!

2) 시중의 봉투모의고사 다~풀어보기 -> 저퀄 문제에도 익숙해지도록 한다

3) 시험 전날용 문제집 준비해두고 전날에도 꼭 풀기

 

 

유튜브 영상 참고하여 정리한 글!

참고 : www.youtube.com/watch?v=-mMK54oUqqQ

 

프로젝트 진행 중 음성을 텍스트로 변환해야 할 부분이 있어서 Google Cloud Speech-to-Text API를 사용해보았다.

1. 환경 설정

여기서 나는 pip install pyaudio가 안돼서 애를 먹었는데 window10환경이라 그럴 수 있다고 한다.
설치되지 않는다면 밑의 명령어들을 순서대로 실행시키면 된다.

  • pip install pipwin
  • pipwin install pyaudio

2. python 코드 실행

아래의 코드를 환경 설정 해주었던 폴더의 env 밖에 넣어준다. (참고로 저는 vscode 사용)
환경설정에 있던 링크에서처럼 python 파일명.py를 하고 마이크에 말을 하면 텍스트로 나오는 모습을 볼 수 있다.

#!/usr/bin/env python

# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Google Cloud Speech API sample application using the streaming API.
NOTE: This module requires the additional dependency `pyaudio`. To install
using pip:
    pip install pyaudio
Example usage:
    python transcribe_streaming_mic.py
"""

# [START speech_transcribe_streaming_mic]
from __future__ import division

import re
import sys

from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
import pyaudio
from six.moves import queue

# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms


class MicrophoneStream(object):
    """Opens a recording stream as a generator yielding the audio chunks."""
    def __init__(self, rate, chunk):
        self._rate = rate
        self._chunk = chunk

        # Create a thread-safe buffer of audio data
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            # The API currently only supports 1-channel (mono) audio
            # https://goo.gl/z757pE
            channels=1, rate=self._rate,
            input=True, frames_per_buffer=self._chunk,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self

    def __exit__(self, type, value, traceback):
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)
        self._audio_interface.terminate()

    def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
        """Continuously collect data from the audio stream, into the buffer."""
        self._buff.put(in_data)
        return None, pyaudio.paContinue

    def generator(self):
        while not self.closed:
            # Use a blocking get() to ensure there's at least one chunk of
            # data, and stop iteration if the chunk is None, indicating the
            # end of the audio stream.
            chunk = self._buff.get()
            if chunk is None:
                return
            data = [chunk]

            # Now consume whatever other data's still buffered.
            while True:
                try:
                    chunk = self._buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break

            yield b''.join(data)


def listen_print_loop(responses):
    """Iterates through server responses and prints them.
    The responses passed is a generator that will block until a response
    is provided by the server.
    Each response may contain multiple results, and each result may contain
    multiple alternatives; for details, see https://goo.gl/tjCPAU.  Here we
    print only the transcription for the top alternative of the top result.
    In this case, responses are provided for interim results as well. If the
    response is an interim one, print a line feed at the end of it, to allow
    the next result to overwrite it, until the response is a final one. For the
    final one, print a newline to preserve the finalized transcription.
    """
    num_chars_printed = 0
    for response in responses:
        if not response.results:
            continue

        # The `results` list is consecutive. For streaming, we only care about
        # the first result being considered, since once it's `is_final`, it
        # moves on to considering the next utterance.
        result = response.results[0]
        if not result.alternatives:
            continue

        # Display the transcription of the top alternative.
        transcript = result.alternatives[0].transcript

        # Display interim results, but with a carriage return at the end of the
        # line, so subsequent lines will overwrite them.
        #
        # If the previous result was longer than this one, we need to print
        # some extra spaces to overwrite the previous result
        overwrite_chars = ' ' * (num_chars_printed - len(transcript))

        if not result.is_final:
            sys.stdout.write(transcript + overwrite_chars + '\r')
            sys.stdout.flush()

            num_chars_printed = len(transcript)

        else:
            print(transcript + overwrite_chars)

            # Exit recognition if any of the transcribed phrases could be
            # one of our keywords.
            if re.search(r'\b(exit|quit)\b', transcript, re.I):
                print('Exiting..')
                break

            num_chars_printed = 0


def main():
    # See http://g.co/cloud/speech/docs/languages
    # for a list of supported languages.
    language_code = 'ko-KR'  # a BCP-47 language tag

    client = speech.SpeechClient()
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=RATE,
        language_code=language_code)
    streaming_config = types.StreamingRecognitionConfig(
        config=config,
        interim_results=True)

    with MicrophoneStream(RATE, CHUNK) as stream:
        audio_generator = stream.generator()
        requests = (types.StreamingRecognizeRequest(audio_content=content)
                    for content in audio_generator)

        responses = client.streaming_recognize(streaming_config, requests)

        # Now, put the transcription responses to use.
        listen_print_loop(responses)


if __name__ == '__main__':
    main()
# [END speech_transcribe_streaming_mic]

3. 실행 화면

'CODING > PYTHON' 카테고리의 다른 글

Python 유용한 링크 정리  (0) 2020.01.14

1. 오류 발생

  • 프로젝트 진행 중 returnType="HashMap"으로 넘길 시에 조회가 되지 않는 오류 발생했고 두 가지의 해결 방법을 찾았다.

    • 첫 번째 방법(권장) : resultMap 사용하기
    • 두 번째 방법 : DTO와 데이터베이스의 컬럼이 정확히 일치하면 HashMap으로 넘길 시에 List로 받더라도 자동 매핑이 되지만, 그게 아닐 때는 키값을 이용하여 넣어주면 된다. (키 값은 Iterator를 통하여 값에 접근)

2. 첫 번째 방법 : ResultMap 사용하기

  • ResultMap은 DB 컬럼명과 DTO의 변수 명이 다를 때 사용한다.

    • resultMap 선언
      • id = 사용할 id 명
      • resultMap type= DTO명
      • column = DTO 변수 명
      • property = 데이터베이스 컬럼 명
    • select 문에서 사용
      • resultMap="resultMap의 id명"
  • 예제 코드

    • USER.xml

      <resultMap id="UserList" type="User">
          <result column="userId" property="USER_ID">
          <result column="userName" property="USER_NAME">
      </resultMap>
      
      <select id="userList" resultMap="UserList">
             select \* from USER
      </select>

3. 두 번째 방법 : Iterator 란?

  • Iterator는 자바의 컬렉션 프레임웍에서 컬렉션에 저장되어 있는 요소들을 읽어오는 방법을 표준화하였는데 그중 하나가 Iterator이다.
  • 자세한 설명 : https://vaert.tistory.com/108
  • 예제 코드
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

// DTO와 DB가 일치하지 않으므로 HashMap List 사용
// Post 자리에는 사용될 객체 이름을 넣어주면 된다. ( 저는 임의로 Post 사용! )
List<HashMap<Object, Post>> result = sqlSession.selectList(NS+"searchPost");

// 가져온 객체들을 저장해서 반환 할 새로운 배열을 선언
List<Post> list = new ArrayList<Post>();

// 받아온 HashMap List를 HashMap에 차례로 넣어준다.
for(HashMap<Object, Post> hash : result){
    // Hash의 value값을 조회 할 key값 가져오기
        Set key = hash.keySet();
    // Iterator에 key를 담는다.
        Iterator iterator = key.iterator();

    // list에 하나씩 담아 줄 새로운 객체 생성
        Post post = new Post();

        // setter 사용
        // iterator.next()를 통하여 값을 접근한다.
        post.setTitle(hash.get(iterator.next()).toString());
        post.setContent(hash.get(iterator.next()).toString());

        // setter를 통하여 값을 다 넣어준 후에는 list에 추가해주기
        list.add(post);

        // hasNext를 통해 다음 KEY값들의 모음으로 넘어간다.

      }
      return list;
}

 

4. 기타 기억할 점

  • 가져오는 값이 Int형일 경우 Integer.parseInt(가져올 값)
  • 그 외 형 변환 오류 발생시 (가져올 값). getClass(). getName()으로 자료형 확인해서 맞춰주기

https://velog.io/@juna-dev/%ED%95%B4%EC%8B%9C%ED%83%9C%EA%B7%B8-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-9ak4xocihh

https://m.blog.naver.com/PostView.nhn?blogId=1ilsang&logNo=221231586062&proxyReferer=https:%2F%2Fwww.google.com%2F

1. PCA알고리즘

https://nittaku.tistory.com/291

 

12. 머신러닝 알고리즘 : 차원축소 - PCA 알고리즘 / 실습

캡쳐 사진 및 글작성에 대한 도움 출저 : 유튜브 - 허민석님 PCA : Principal Component Analysis (주 성분 분석) PCA는 언제 많이 사용할까? 바로 시각화를 위해 사용한다. 여태껏 시각화를 위해 feature 2개만..

nittaku.tistory.com

2. 점프 투 파이썬

책을 무료로 볼 수 있는 위키독스

 https://wikidocs.net/book/1

 

0. 인트로

1. 내가 준비한 것

2. 분위기

3. 후기

 

 

0. 인트로

*싸피 면접의 정보를 유출하지 않겠다는 보안 규약에 따라 작성한 글이므로 면접에 관한 정보는 없음*

발표를 기다리던 중 후기를 기록하고 싶다는 생각이 들어 작성하게 되었다ㅎㅅㅎ

 

1. 내가 준비한 것

혹시나 싶어서 1분 자기소개를 준비해서 외워갔다.

싸피에 지원하게 된 이유와 나의 강점에 대해서 준비함!

사전 학습 내용을 정리했던 노트도 챙겨서 기차타는 동안 두 번 정도 훑었다.

긴장하면 머리가 하얘지는 멍퉁이라 자기소개서 적었던 것을 핸드폰에 복사해놓고 예상 질문들과 답변을 메모장에 적어서 대략의 스토리를 외우려고 노력했다.

하다보니 자꾸 회사 면접 보듯이 생각하게 되는데, 회사 면접이 아니라 교육생을 뽑는 것임을 인지​하려고 노력했다.

 

2. 분위기

원래는 단정한 복장이라고 공지해주시는데,

최근에 정장 입을 일이 많았어서 진저리가 난 탓에 당일 아침까지도 고민하다가 결국 정장 말고 무난한 가디건에 슬랙스를 입고 갔다. 막상 갔더니 거의 다 정장을 입고 오셔서 쬐금 후회했지만 크게 상관은 없는 것 같다ㅎㅎ

같은 시간에 면접보는 분들과 굉장히 어색함,,,,민망함,,,무튼 그렇다,,,

간식이 준비되어 있어서 먹고 싶었는데 먹었다간 체할 것 같아서 포기했다.ㅠ

지역에 따라 소정의 면접비를 주신다.

 

3. 후기

솔직히 결과는 정말 모르겠다. 나름대로 간절함을 어필했다곤 생각하지만 좀 더 준비해갈걸 후회됐다 ㅠ_ㅠ

붙고 싶은 만큼 열심히 준비한다면 꼭 면접에 도움이 될 거라 생각한다.

하지만 싸피 설명회에서 말씀해주셨듯이 면접을 위해 비싼 강의를 들을 필요는 없을 듯?

평소에 면접볼 때 많이 긴장하는 사람은 단기 면접 스터디를 준비하는 것도 좋을 것 같다.

(내가 했다는 것은 아니지만 면접 스터디는 어디를 준비하든 취준력을 길러준다)

카카오 오픈채팅방에 싸피 준비하는 방이 많으니 한 개 정도는 들어가서 스터디 구하면 된다. 대신에 온갖 뇌피셜이 난무하는 곳이라 정보는 얻을 수 없다. 꼭 붙어서 싸피생 교육 후기로 돌아올 수 있길바라며 끝!!!!

+ Recent posts