www.acmicpc.net/problem/1168

 

1168번: 요세푸스 문제 2

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 100,000)

www.acmicpc.net

1158번 요세푸스 문제와 달리 세그먼트 트리를 구현해야만 통과가 가능하다.

푸는데는 성공했지만 내 역량 밖이라 더 공부하고 다시 풀어야 할 것 같다.

코드는 내가 완전히 익히면 공개해야겠다.

 

아래는 문제풀 때 참고했던 글들 >>>

1. 세그먼트 트리 정리

www.crocus.co.kr/648

 

세그먼트 트리(Segment Tree)

세그먼트 트리(Segment Tree)는 요청하는 쿼리에 대해 방식이 달라질 수 있으나, 모든 쿼리를 다룰 수 없기에 구간 합에 대한 세그먼트 트리를 정리해 두었습니다. 내용이 길지만 그만큼 자세히 설

www.crocus.co.kr

2. c++로 구현 한 분들

cocoon1787.tistory.com/433

 

[C/C++] 백준 1168번 - 요세푸스 문제 2 (세그먼트 트리)

<코드> #include #include using namespace std; int N, K; int a, b; int seg[(1< > N >> K; init(1, 1, N); // (루트노드, 시작, 끝) int index = 1; cout << "<"; for (int i = 0; i < N; i++) { // 다음 순서..

cocoon1787.tistory.com

suri78.tistory.com/274

 

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

[백준]1107번 리모컨 파이썬  (0) 2021.02.23
[백준] 1967번 트리의 지름 파이썬  (0) 2021.02.20

www.acmicpc.net/problem/1107

 

1107번: 리모컨

첫째 줄에 수빈이가 이동하려고 하는 채널 N (0 ≤ N ≤ 500,000)이 주어진다.  둘째 줄에는 고장난 버튼의 개수 M (0 ≤ M ≤ 10)이 주어진다. 고장난 버튼이 있는 경우에는 셋째 줄에는 고장난 버튼

www.acmicpc.net

리모컨을 부수고 싶었던 문제다ㅠ

 

풀이

  1. 완전 탐색
  2. +- 다 가능하므로 범위는 1000000까지
  3. 초기 값인 100에서 목표 값 까지 모든 버튼이 고장난 경우를 생각하여 최소 값을 목표 값 - 100으로 지정 해준다
  4. -> 이걸로 목표가 100일 때 예외 처리도 가능
주의점
- 고장난 리모컨이 없을 경우엔 고장난 버튼 입력을 받지 않아야 하므로 if문으로 예외 처리 해주기
import sys
input = sys.stdin.readline

num = int(input())
M = int(input())

array = [0 for _ in range(10)]
flag = True
if M != 0 :
    button = list(map(int, input().split()))
    for i in button:
        array[i] = 1

cnt = abs(num-100)

for i in range(1000001):
    list_i = list(str(i))
    flag = False
    for j in list_i:
        if array[int(j)]==0 : continue
        else:
            flag = True
            break

    if not flag:
        tmp = abs(num-i) + len(list_i)
        if cnt > tmp:
            cnt = tmp
print(cnt)

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

프로젝트 진행 중 음성을 텍스트로 변환해야 할 부분이 있어서 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

+ Recent posts