728x90
반응형

7/ 02 파이썬 공부
1. 백준 15025 Judging Moose
When determining the age of a bull moose, the number of tines (sharp points), extending from the main antlers, can be used. An older bull moose tends to have more tines than a younger moose. However, just counting the number of tines can be misleading, as a moose can break off the tines, for example when fighting with other moose. Therefore, a point system is used when describing the antlers of a bull moose.

The point system works like this: If the number of tines on the left side and the right side match, the moose is said to have the even sum of the number of points. So, “an even 6-point moose”, would have three tines on each side. If the moose has a different number of tines on the left and right side, the moose is said to have twice the highest number of tines, but it is odd. So “an odd 10-point moose” would have 5 tines on one side, and 4 or less tines on the other side.

Can you figure out how many points a moose has, given the number of tines on the left and right side?

The input contains a single line with two integers ℓ and r, where 0 ≤ ℓ ≤ 20 is the number of tines on the left, and 0 ≤ r ≤ 20 is the number of tines on the right.

Output a single line describing the moose. For even pointed moose, output “Even x” where x is the points of the moose. For odd pointed moose, output “Odd x” where x is the points of the moose. If the moose has no tines, output “Not a moose”

>>>해석
무스의 나이는 가장 큰 뿔에서 뻗어 나온 가지(뾰족한 부분)의 수로 확인할 수 있습니다. 
나이가 많은 무스는 보통 나이가 어린 무스보다 많은 가지를 지니고 있습니다. 
하지만 다른 무스와 싸우거나 할 때 가지가 손상될 수 있으므로, 가지의 수만 가지고 판단하는 것은 정확하지 않습니다. 따라서 무스의 뿔에는 포인트 시스템이 적용됩니다.

포인트 시스템은 아래와 같습니다: 
만약 왼쪽과 오른쪽의 가지 수가 같다면, 그 무스는 짝수 포인트 합을 지녔다고 말합니다. 
따라서 "짝수 6포인트 무스"는 양쪽에 3개의 가지를 가진 무스입니다. 
만약 무스의 왼쪽과 오른쪽 가지 수가 다르다면, 그 무스는 가지가 많은 쪽을 기준으로 2배 값의 홀수 포인트 합을 지닌다고 말합니다. 따라서 "홀수 10포인트 무스"는 한쪽에 5개의 가지가 있고, 반대쪽에 4개 이하의 가지가 있는 무스입니다.

왼쪽과 오른쪽 가지의 수가 주어졌을 때, 무스가 어떤 포인트를 지니는지 알 수 있습니까?

한 줄에 두 정수 l, r이 주어지는데, 0 <= l <= 20은 왼쪽 가지의 수를, 0 <= r <= 20은 오른쪽 가지의 수를 뜻합니다.

무스를 표현하는 한 줄을 출력합니다. 
짝수 포인트 무스에 대해서는, 무스가 x포인트라 할 때 "Even x"를 출력합니다. 
홀수 포인트 무스에 대해서는, 무스가 x포인트라 할 때 "Odd x"를 출력합니다. 
무스가 가지를 가지고 있지 않다면, "Not a moose"를 출력합니다. 

>>>코드

l, r = map(int, input().split())
if l == 0 and r == 0:
    print('Not a moose')
elif l == r:
    print('Even %d' %(l+r))
else:
    print('Odd %d' %(max(l,r)*2))



2. 백준 24751 Betting
The popular streaming platform switch.tv just unveiled their newest feature: switch betting.  Streamers can now get their viewers to bet on two different options using switch points (patented).

Each viewer bets some number of switch points for one of the two options. The total amount of switch points bet by everyone is called the prize pool. The streamer will choose one of the options as the winner and the prize pool is split (not necessarily equally) between all the viewers who bet on that option; the more you bet on the option, the more of the prize pool you receive. In particular, if you contributed p% of all the bets for one of the options and that option wins, then you receive p% of the total prize pool.

The switch.tv team has come to you to compute what the switch point payout is for each viewer if their selected option wins. To do this, they ask you to find the switch-payout-ratio for each of the two options. Since the payout to each viewer is proportional to the number of switch points they put into the bet, the switch team will be able to use this ratio to determine each viewer's winnings.

For example, suppose a streamer created a switch bet where three viewers participated. Two viewers bet 10 and 30 switch points on option one and the last viewer bets 10 switch points on option two. We can see that option one has 80% of the bets and option two has 20% of the bets.

If option one wins, then the two viewers who bet on that receive 12.5 and 37.5 switch points, respectively, which means that the switch-payout-ratio is 1:1.25 for option one. If option two wins, then the single viewer who bets on that receives 50 switch points, which means that the switch-payout-ratio is 1:5.

Given the percentage of total bets for option one, help switch.tv by computing the switch-payout-ratio for the two options.

The input consists of one integer a (0 < a < 100), which is the percentage of switch points bet on option one.

출력
For each option (option one, then option two), display the number x such that 1:x is the switch-payout-ratio for that option. Your answer should have an absolute or relative error of at most 
$10^{-3}$.

>>>해석
유명한 스트리밍 플랫폼 스위치 TV가 새로운 기능을 공개했습니다: 스위치 베팅. 스트리머는 이제 시청자가 두 가지 선택지를 두고 (스위치만의) 스위치 포인트를 이용해 베팅하도록 만들 수 있습니다.

각 시청자는 두 선택지 중 하나에 스위치 포인트를 걸 수 있습니다. 
모든 사람이 건 스위치 포인트의 총 합계를 상금이라 부릅니다. 스트리머는 하나의 선택지를 승자로 만들어 그 선택지를 선택한 시청자들에게 (꼭 동일하지는 않게) 상금을 분배합니다; 당신이 선택지에 더 많은 돈을 걸었다면, 더 많은 상금을 가져갑니다. 더 자세히 말하자면, 당신이 하나의 선택지에 걸린 금액에 p%만큼 기여했고 그 옵션이 이겼다면, 당신은 상금의 p%를 가져갑니다.

스위치 TV 팀은 당신이 하나의 선택지가 승리했을 때 각 시청자가 상금으로 얼마만큼 가져가는지 계산하기를 바랍니다. 이를 위해서, 그들은 두 가지 선택지에 대해 스위치 포인트와 상금의 비율을 계산하려 합니다. 각 시청자에게 돌아가는 상금의 비율은 그들이 건 돈의 비율에 비례하기에, 스위치 팀은 각 시청자가 가져가는 상금의 양을 판단할 때 이 비율을 사용할 것입니다.

예를 들어, 스트리머가 세 시청자가 참여한 스위치 베팅을 했다고 가정합시다. 두 시청자가 각각 10 스위치 포인트와 30 스위치 포인트를 첫 번째 선택지에 걸었고, 남은 시청자는 두 번째 선택지에 10 스위치 포인트를 걸었습니다. 당신은 첫 번째 선택지가 80%의 금액을 차지하고, 두 번째 선택지가 20%의 금액을 차지함을 알 수 있습니다.

첫 번째 선택지가 이길 경우, 이 선택지를 고른 두 시청자는 각각 12.5, 37.5 스위치 포인트를 가져가므로 스위치 포인트와 상금의 비율은 1:1.25가 됩니다. 두 번째 선택지가 이길 경우, 단 한 명의 시청자가 50 스위치 포인트를 가져가므로 스위치 포인트와 상금의 비율은 1:5가 됩니다.

상금에서 첫 번째 선택지에 걸린 금액이 차지하는 비율이 퍼센트로 주어질 때, 스위치 TV 팀이 두 가지 선택지에 대해 스위치 포인트와 상금의 비율을 계산할 수 있도록 도와줍시다.

상금에서 첫 번째 선택지에 걸린 금액이 차지하는 비율을 퍼센트로 나타낸 하나의 정수 a (0 < a < 100)가 주어집니다.

각 선택지에 대해 (첫 번째 선택지, 두 번째 선택지 순서로), 1:x가 그 선택지의 스위치 포인트와 상금의 비율을 나타내는 숫자 x를 출력합니다. 당신의 답은 최대 10 ^ (-3)의 절대 또는 상대 오차를 지닐 수 있습니다.

>>>코드

a = float(input())
print(1+(100-a)/a)
print(1+a/(100-a))



3. 백준 17863 FYI
In the United States of America, telephone numbers within an area code consist of 7 digits: the prefix number is the first 3 digits and the line number is the last 4 digits. Traditionally, the 555 prefix number has been used to provide directory information and assistance as in the following examples:

- 555-1212
- 555-9876
- 555-5000
- 555-7777

Telephone company switching hardware would detect the 555 prefix and route the call to a directory information operator. Now-a-days, telephone switching is done digitally and somewhere along the line a computer decides where to route calls.

For this problem, write a program that determines if a supplied 7-digit telephone number should be routed to the directory information operator, that is, the prefix number is 555.

The input consists of a single line containing a 7-digit positive integer N, 
(1000000 <= N <= 9999999).
The single output line consists of the word YES if the number should be routed to the directory information operator or NO if the number should not be routed to the directory information operator.

>>>해석
미국에서 지역 내 전화번호는 7자리로 이루어져 있습니다: 
첫 세 자리를 앞자리 번호라 부르고, 끝 네 자리를 뒷자리 번호라 부릅니다. 
아래의 예시와 같이, 전통적으로 앞자리 번호가 555인 번호는 전화번호 제공 및 안내에 사용됩니다.

- 555-1212
- 555-9876
- 555-5000
- 555-7777

전화 교환기는 앞자리 번호가 555인 번호를 탐지해 담당 상담원에게 전화를 연결합니다. 
현대 사회에서 전화 교환은 디지털로 이루어지므로 특정 단계에서 컴퓨터가 전화를 어디로 돌릴지 결정합니다.

이 문제에서 당신은 제공된 일곱 자리 전화번호가 앞자리 번호가 555이므로 담당 상담원에게 연결해야 하는 번호인지 판정하는 프로그램을 작성합니다.

한 줄에 일곱 자리 자연수 N (1000000 <= N <= 9999999)이 주어집니다.
한 줄에 전화번호가 담당 상담원에게 연결돼야 한다면 YES를, 그러지 않아도 된다면 NO를 출력합니다.

>>>코드

n = input()
if n[:3] == '555':
    print('YES')
else:
    print('NO')


4. 백준 6841 I Speak TXTMSG
Text messaging using a cell phone is popular among teenagers. The messages can appear peculiar because short forms and symbols are used to abbreviate messages and hence reduce typing.

For example, “LOL” means “laughing out loud” and “:-)” is called an emoticon which looks like a happy face (on its side) and it indicates chuckling. This is all quite a mystery to some adults.

Write a program that will continually input a short form and output the translation for an adult using the following translation table:

Short Form Translation
CU see you
:-) I’m happy
:-( I’m unhappy
;-) wink
:-P stick out my tongue
(~.~) sleepy
TA totally awesome
CCC Canadian Computing Competition
CUZ because
TY thank-you
YW you’re welcome
TTYL talk to you later

The user will be prompted to enter text to be translated one line at a time. When the short form “TTYL” is entered, the program ends. Users may enter text that is found in the translation table, or they may enter other words. All entered text will be symbols or upper case letters. There will be no spaces and no quotation marks.

The program will output text immediately after each line of input. If the input is one of the phrases in the translation table, the output will be the translation; if the input does not appear in the table, the output will be the original word. The translation of the last short form entered “TTYL” should be output.

>>>해석
휴대전화를 이용한 문자 메시지는 십대들 사이에서 인기가 있습니다. 
짧은 형식과 기호를 사용하여 메시지를 축약하여 입력을 줄이기 때문에 메시지가 이상하게 보일 수 있습니다.

예를 들어 "LOL"은 "큰 소리로 웃다"라는 뜻이고 ":-)"는 (옆에서) 행복한 얼굴처럼 보이는 이모티콘이라고 하며 웃는 것을 나타냅니다. 이것은 일부 어른들에게는 모두 매우 미스터리입니다.

다음 번역표를 사용하여 연속적으로 짧은 형식을 입력하고 번역을 출력하는 프로그램을 작성하십시오.

줄임말 의미
CU see you
:-) I’m happy
:-( I’m unhappy
;-) wink
:-P stick out my tongue
(~.~) sleepy
TA totally awesome
CCC Canadian Computing Competition
CUZ because
TY thank-you
YW you’re welcome
TTYL talk to you later

한 번에 한 줄씩 번역할 텍스트를 입력하라는 메시지가 사용자에게 표시됩니다. 
약식 "TTYL"을 입력하면 프로그램이 종료됩니다. 
사용자는 번역표에서 찾은 텍스트를 입력하거나 다른 단어를 입력할 수 있습니다. 
입력한 모든 텍스트는 기호 또는 대문자입니다. 공백과 따옴표가 없습니다.

프로그램은 각 입력 줄 직후에 텍스트를 출력합니다. 
입력이 번역 테이블의 구 중 하나인 경우 출력은 번역이 됩니다. 
입력이 테이블에 나타나지 않으면 출력은 원래 단어가 됩니다. 
"TTYL"을 입력한 마지막 짧은 형식의 번역이 출력되어야 합니다.

>>>코드

l = {'CU':'see you',':-)':'I’m happy',':-(':'I’m unhappy',';-)':'wink',':-P':'stick out my tongue','(~.~)':'sleepy','TA':'totally awesome','CCC':'Canadian Computing Competition','CUZ':'because','TY':'thank-you','YW':'you’re welcome','TTYL':'talk to you later'}
while True:
    s = input()
    if s == 'TTYL':
        print(l[s])
        break
    elif s in l:
        print(l[s])
    else:
        print(s)


5. 백준 5928 Contest Timing
Bessie the cow is getting bored of the milk production industry, and wants to switch to an exciting new career in computing. To improve her coding skills, she decides to compete in the on-line USACO competitions. Since she notes that the contest starts on November 11, 2011 (11/11/11), she decides for fun to download the problems and begin coding at exactly 11:11 AM on 11/11/11.

Unfortunately, Bessie's time management ability is quite poor, so she wants to write a quick program to help her make sure she does not take longer than the 3 hour (180 minute) time limit for the contest. Given the date and time she stops working, please help Bessie compute the total number of minutes she will have spent on the contest.

Input
Line 1: This line contains 3 space-separated integers, D H M, specifying the date and time at which Bessie ends the contest. D will be an integer in the range 11..14 telling the day of the month; H and M are hours and minutes on a 24-hour clock (so they range from H=0,M=0 at midnight up through H=23,M=59 at 11:59 PM).

Output
Line 1: The total number of minutes spent by Bessie in the contest, or -1 if her ending time is earlier than her starting time.

>>>해석
소 베시는 우유 생산 산업에 종사하는 것도 지쳐, 컴퓨터 관련 흥미로운 커리어를 새로 시작하려 합니다. 
코딩 실력을 늘리기 위해, 베시는 온라인 USACO 대회에 참가하기로 했습니다. 
대회가 2011년 11월 11일(11/11/11)에 시작한다는 것을 알게 돼, 
베시는 재미 삼아 11/11/11 오전 11:11에 문제를 다운로드 받아 코딩을 시작하기로 했습니다.

안타깝게도 베시는 시간 관리를 잘하는 편이 아니라, 대회 시간 제한인 3시간(180분)을 넘기지 않도록 도와주는 프로그램을 빠르게 작성하려 합니다. 날짜와 베시가 대회를 마친 시간이 주어질 때, 베시를 도와 그녀가 대회에 투자한 시간을 분으로 계산합시다.

입력 
첫째 줄: 베시가 대회를 마치는 시간을 나타낸 세 정수 D H M이 공백으로 나뉘어 주어집니다. D는 날짜의 일을 나타내는 11~14 사이의 정수이며, H와 M은 24시간 단위 기준으로 날짜의 시간과 분을 나타냅니다. (따라서 범위는 자정인 H = 0, M = 0부터 오후 11시 59분을 나타내는 H = 23, M = 59까지입니다.)

출력
첫째 줄: 베시가 대회에 투자한 총 시간을 분으로 출력하거나, 끝나는 시간이 시작 시간보다 빠르다면 -1을 출력합니다.

>>>코드

d, h, m = map(int, input().split())
t = d*24*60+h*60+m-(11*24*60+11*60+11)
if t<0:
    print(-1)
else:
    print(t)



6. 백준 26742 Skarpetki
W Bajtocji noszenie skarpetek o różnych kolorach i wzorach przestało już być modne. Teraz nastała moda na noszenie wyłącznie dwóch skarpetek białych lub dwóch skarpetek czarnych.

Bajtazar, który zawsze stara się nadążać za trendami w modzie, zakupił dużo pojedynczych skarpetek (białych i czarnych). Chciałby wiedzieć ile jednokolorowych (albo białych albo czarnych) par skarpetek uda mu się skompletować.

Ponieważ Bajtazar nie radzi sobie za dobrze ze zliczaniem swoich skarpetek, zwrócił się do Ciebie z prośbą o pomoc. Napisz program, który wczyta ciąg opisujący skarpetki Bajtazara i wyznaczy liczbę jednokolorowych par skarpetek, które można z nich skompletować.

W pierwszym (jedynym) wierszu wejścia znajduje się niepusty ciąg liter B oraz C oznaczających kolory kolejnych skarpetek Bajtazara (B oznacza skarpetkę białą, a C skarpetkę czarną).
Długość ciągu nie przekracza 1 000 000 znaków.

W pierwszym (jedynym) wierszu wyjścia należy wypisać jedną nieujemną liczbę całkowitą – liczbę par skarpetek jednokolorowych, jakie można stworzyć ze skarpetek opisanych na wejściu.

>>>해석
Byteotia에서 다른 색상과 패턴의 양말을 신는 것은 더 이상 유행이 아닙니다. 
지금은 흰 양말 두 개나 검은 양말 두 개만 신는 것이 유행입니다.

항상 패션 트렌드를 따라가려고 노력하는 Byteasar는 단일 양말 (흰색과 검정색)을 많이 구입했습니다. 
그는 자신이 완성할 수 있는 단일 색상(흰색 또는 검정색) 양말을 몇 켤레나 알고 싶어합니다.

Byteasar는 양말을 세는 데 능숙하지 않기 때문에 도움을 요청했습니다. Byteasar의 양말을 설명하는 문자열을 읽고 그로부터 조립할 수 있는 단색 양말 쌍의 수를 결정하는 프로그램을 작성하십시오.

입력의 첫 번째이자 유일한 줄에는 Byteasar의 양말 색상을 나타내는 비어 있지 않은, B와 C로만 구성된 문자열이 입력됩니다.B는 흰색 양말을 나타내고 C는 검은색 양말을 나타냅니다. 
문자열의 길이는 1,000,000자를 초과하지 않습니다.

입력에서 설명된 양말들에서 만들 수 있는 단색 양말 쌍의 수를 한 줄에 출력합니다.

>>>코드

s = input()
print(s.count('B')//2 + s.count('C')//2)



7. 백준 24294 ГРАДИНА 
Цветин живее на поле, разделено на квадратни клетки с размер 1x1. Той много обича цветята, затова често прави нови лехи за тях. Цветните лехи имат специална форма: те са два правоъгълника, поставени един до друг, така че левите им страни образуват една права линия (фигурата вдясно).

За да украси новата леха, Цветин решил да постави по целия ѝ периметър плочки, със същия размер като клетката на полето, в което живее

Напишете програма garden, която намира броя плочки, които са необходими на Цветин.

На първите четири реда на стандартния вход са записани четири цели числа w1, h1, w2 и h2 - съответно ширина и височина на първия правоъгълник, ширина и височина на втория правоъгълник, от които е направена лехата.

На първия ред на стандартния изход програмата трябва да изведе едно цяло число - брой на плочките, необходими на Цветин да украси леха с дадения размер.

>>>해석
즈베틴은 1 * 1 크기의 사각형 칸으로 나뉘어진 정원에 있습니다. 
즈베틴은 꽃을 좋아해, 종종 화단을 만듭니다. 화단은 항상 특별한 모양을 지닙니다: (그림 참조) 
두 직사각형이 왼쪽이 직선을 이루도록 붙어 배치된 모양입니다.
새로운 화단을 꾸미기 위해, 즈베틴은 둘레에 그가 있는 정원의 한 칸과 같은 크기의 타일을 깔려고 합니다.
즈베틴이 깔아야 하는 타일의 수를 구하는 프로그램을 작성합시다.

첫 네 개의 줄에 화단을 이루는 첫 번째 직사각형의 너비와 높이, 두 번째 직사각형의 너비와 높이를 각각 나타내는 w1, h1, w2, h2가 표준 입력으로 주어집니다.
첫 줄에 즈베틴이 주어진 사이즈의 화단을 꾸미는 데 필요한 타일의 수를 정수로 출력합니다.

>>>코드

w1 = int(input())
h1 = int(input())
w2 = int(input())
h2 = int(input())
print(2*(h1+h2+max(w1, w2)) + 4)



8. 백준 24356 ЧАСОВНИК
Група ученици излезли на разходка след училище. При тръгване електронният часовник на Тони показвал t1 часа и m1 минути. Те обикаляли около езеро. Когато се прибрали, Тони погледнал часовника и видял, че е t2 часа и m2 минути. Разходката продължила по-малко от едно денонощие и наймалко може да е била 0 минути. Пълна обиколка на езерото се прави точно за половин час.

и точно за половин час. Напишете програма chas, която въвежда началния и крайния час на разходката, и отпечатва времето m в минути, което е изминало и броя n на пълните обиколки, които са направили учениците за това време.

От стандартния вход се въвеждат последователно четири цели числа t1, m1, t2, m2.
На стандартния изход програмата трябва да изведе две цели числа m и n - търсеното време в минути и броя на пълните обиколки. Числата са разделени с един интервал.

>>>해석
학생들이 방과 후에 산책을 나섰습니다. 토니의 디지털 시계는 t1시 m1분을 가리키고 있습니다. 
학생들은 호수 주변을 걸었습니다. 집에 도착해, 토니가 다시 시계를 보니 t2시 m2분이었습니다. 
산책 시간은 하루보다 짧으며 0분이었을 수도 있습니다. 호수를 한 바퀴 도는 데에는 30분이 걸립니다.

산책을 시작한 시간과 산책이 끝난 시간을 입력 받아 산책에 걸린 시간 m분과 학생들이 호수를 완전히 한 바퀴 돈 횟수 n번을 출력하는 프로그램을 작성합시다.

표준 입력으로 네 정수 t1, m1, t2, m2가 순서에 맞게 주어집니다.
프로그램은 각각 분으로 표기한 총 산책 시간과 호수를 완전히 한 바퀴 돈 횟수인 두 정수 m과 n을 출력합니다. 숫자는 공백으로 구분됩니다.

>>>코드

t1, m1, t2, m2 = map(int, input().split())
t = t2*60+m2-t1*60-m1
if t<0:
    t = 1440 + t
print(t, t//30)



9. 백준 21354 Äpplen och päron
Axel vill tävla med Petra om vem som sålt flest äpplen respektive päron, men Petra tycker inte att man kan "jämföra äpplen och päron". De kommer överens om att de istället ska jämföra hur mycket de tjänat. De ber dig skapa ett program som skriver ut vem som tjänat mest. Äpplen kostar 7 kronor styck och päron 13 kronor styck.

En rad med två heltal A,P (0 <= A,P <= 1000), antalet äpplen Axel har lyckats sälja, och antalet päron Petra har lyckats sälja. 

Programmet ska skriva ut en rad med en sträng: den person som har tjänat mest, "Axel" eller "Petra". Om de sålt för lika mycket ska du skriva "lika".

>>>해석
악셀은 페트라와 누가 사과 또는 배를 더 많이 팔았는지 대결하고 싶어하지만, 페트라는 "사과와 배는 비교할 수 없다"고 생각합니다. 그들은 대신 누가 더 돈을 많이 벌었는지 대결하기로 했습니다. 
그들은 당신에게 누가 더 많이 벌었는지 출력하는 프로그램을 작성해 달라고 부탁합니다. 
사과의 가격은 7 스웨덴 크로나이며, 배의 가격은 13 스웨덴 크로나입니다.

한 줄에 악셀이 판 사과의 수와 페트라가 판 배의 수를 나타내는 두 정수 A, P (0 <= A, P <= 1000)가 주어집니다. 프로그램은 한 줄에 문자열을 출력합니다: "Axel"과 "Petra" 중 돈을 더 많이 번 사람의 이름. 
둘이 같은 금액을 팔았다면, "lika"를 출력합니다. 

>>>코드

apple, pear = map(int, input().split())
if apple*7>pear*13:
    print('Axel')
elif apple*7<pear*13:
    print('Petra')
else:
    print('lika')



10. 백준 18414 X に最も近い値 (The Nearest Value)
整数 X, L, R が与えられる. L 以上 R 以下の整数のうち,X との差の絶対値が最も小さいものを出力せよ.
そのような整数はちょうど 1 つだけ存在することが証明できる.

入力は以下の形式で標準入力から与えられる.

X L R

L 以上 R 以下の整数のうち,X との差の絶対値が最も小さいものを出力せよ.

>>>해석
정수 X, L, R이 주어집니다. L 이상 R 이하의 정수 중, X와의 차의 절댓값이 가장 작은 것을 출력합시다. 
그런 정수가 단 하나 존재함은 증명 가능합니다.

아래의 형식으로 표준 입력이 주어집니다. 

X L R

L 이상 R 이하의 정수 중, X와의 차의 절댓값이 가장 작은 것을 출력합시다.

>>>코드

x, l, r = map(int, input().split())
if x <= l:
    print(l)
elif x >= r:
    print(r)
else:
    print(x)



11. 백준 20839 Betygsättning
Pelle är programmeringslärare på Pelles Optimeringsskola (PO-skolan). 
Han håller nu på att sätta betyg på sina elever i kursen Optimering 1.

Betygsättning går till på följande vis. Totalt finns det x A-kriterier, y C-kriterier och z E-kriterier som används. För att få betyget E måste man uppfylla samtliga E-kriterier. För att få betyget C måste man uppfylla samtliga C- och E-kriterier. För att få betyget A måste man uppfylla samtliga A-, C- och E-kriterier.

Dessutom finns det två speciella betyg. Om man uppfyller alla E-kriterier och minst hälften av C-kriterierna får man ett D. Om man uppfyller alla E- och C-kriterier och minst hälften av A-kriterierna får man ett B.

Pelle tycker det är väldigt jobbigt att sätta betyg, och behöver din hjälp. Skriv ett program som tar emot antalet A-, C- och E-kriterier en viss elev har uppfyllt och skriver ut vilket betyg eleven ska ha. Du kan anta att eleven alltid fick minst E i kursen.

På första raden står tre heltal 1 <= x <= 30, 1 <= y <= 30 och 1 <= z <= 30, antalet A-, C- och E-kriterier som finns. På den andra raden står tre heltal 0 <= x' <= x, 0 <= y' <= y och 0 <= z' <= z, antalet A-, C- och E-kriterier som eleven har uppfyllt.

Programmet ska skriva ut en bokstav: A, B, C, D, eller E.

>>>코드
펠레는 '펠레의 최적화 학교 (PO 스쿨)'의 프로그래밍 교사입니다. 
그는 현재 최적화 1 수업의 학생의 성적을 매기는 중입니다.

성적은 다음과 같은 방식으로 매겨집니다. x개의 기준 A, y개의 기준 C, z개의 기준 E가 있습니다. 
E 등급을 받으려면, 모든 기준 E를 만족해야 합니다. 
C 등급을 받으려면, 모든 기준 C와 기준 E를 만족해야 합니다. 
A 등급을 받으려면, 모든 기준 A, 기준 C, 기준 E를 만족해야 합니다.

추가로 특별 등급이 2개 있습니다. 
모든 기준 E를 만족하고 절반 이상의 기준 C를 만족하면 D 등급이 부여됩니다. 
만약 모든 기준 E와 기준 C를 만족하고 절반 이상의 기준 A를 만족한다면 B 등급이 부여됩니다.  

펠레는 점수를 매기는 게 굉장히 어렵다는 것을 깨닫고, 당신에게 도움을 요청합니다. 특정 학생이 충족한 기준 A, 기준 C, 기준 E의 수를 입력 받아 그 학생이 어떤 등급을 받는지 출력하는 프로그램을 작성합시다. 
특정 학생이 최소 E 등급은 받음은 보장됩니다.

첫 줄에 기준 A, 기준 C, 기준 E의 수를 각각 의미하는 1 <= x <= 30, 1 <= y <= 30, 1 <= z <= 30이 주어집니다. 둘째 줄에는 학생이 만족한 기준 A, 기준 C, 기준 E의 수를 각각 의미하는 0 <= x' <= x, 0 <= y' <= y, 0 <= z' <= z가 주어집니다.

프로그램은 문자 A, B, C, D, 또는 E를 출력합니다.

>>>코드

a, c, e = map(float, input().split())
aa, cc, ee = map(int, input().split())
if aa == a and cc == c and ee == e:
    print('A')
elif aa >= a/2 and cc == c and ee == e:
    print('B')
elif cc == c and ee == e:
    print('C')
elif cc >= c/2 and ee == e:
    print('D')
else:
    print('E')


12. 백준 21665 Миша и негатив
Миша уже научился хорошо фотографировать и недавно увлекся программированием. Первая программа, которую он написал, позволяет формировать негатив бинарного черно-белого изображения.

Бинарное черно-белое изображение – это прямоугольник, состоящий из пикселей, каждый из которых может быть либо черным, либо белым. Негатив такого изображения получается путем замены каждого черного пикселя на белый, а каждого белого пикселя – на черный.

Миша, как начинающий программист, написал свою программу с ошибкой, поэтому в результате ее исполнения мог получаться некорректный негатив. Для того чтобы оценить уровень несоответствия получаемого негатива изображению, Миша начал тестировать свою программу. 

В качестве входных данных он использовал исходные изображения. Сформированные программой негативы он начал тщательно анализировать, каждый раз определяя число пикселей негатива, которые получены с ошибкой. 

Требуется написать программу, которая в качестве входных данных использует исходное бинарное черно-белое изображение и полученный Мишиной программой негатив, и на основе этого определяет количество пикселей, в которых допущена ошибка.

Первая строка входного файла содержит целые числа n и m (1 ≤ n, m ≤ 100) – высоту и ширину исходного изображения (в пикселях).

Следующие n строк содержат описание исходного изображения. Каждая строка состоит из m символов «B» и «W». Символ «B» соответствует черному пикселю, а символ «W» – белому.

Далее следует пустая строка, а после нее – описание изображения, выведенного Мишиной программой в том же формате, что и исходное изображение. 

В выходной файл необходимо вывести число пикселей негатива, которые неправильно сформированы Мишиной программой.

>>>해석
사진을 잘 찍는 미샤는 최근에 프로그래밍에 흥미가 생겼습니다. 
미샤는 첫 프로그램으로 이진 흑백 이미지를 반전시키는 프로그램을 작성했습니다. 

이진 흑백 이미지는 검은색 또는 흰색인 픽셀로 이루어진 직사각형 형태입니다. 
이 이미지의 반전 이미지는 모든 검은색 픽셀을 흰색으로, 모든 흰색 픽셀을 검은색으로 바꾼 이미지입니다.

초보 프로그래머인 미샤의 프로그램에는 오류가 있어 제대로 반전되지 못한 이미지를 반환합니다. 프로그램이 반환한 이미지와 정확한 반전 이미지의 차이를 평가하기 위해 미샤는 프로그램을 테스트하기 시작합니다.

프로그램은 원래 이미지를 입력으로 사용합니다. 
테스트마다 미샤는 잘못 변환된 반전 픽셀의 수를 세며 프로그램이 생성한 반전 이미지를 면밀히 검토합니다.

본래 이진 이미지와 미샤의 프로그램이 생성한 반전 이미지를 입력으로 받아, 오류가 있는 픽셀의 수를 계산하는 프로그램을 작성합시다.

첫 줄에 (픽셀로 나타낸) 원래 이미지의 높이와 너비를 나타내는 정수 n과 m이 주어집니다. 
(1 <= n, m <= 100)
다음 n개의 줄에 원래 이미지가 묘사됩니다. 각 줄은 "B" 또는 "W"인 m개의 문자로 이루어져 있습니다. "B"는 검은 픽셀을, "W"는 흰 픽셀을 나타냅니다.

공백 한 줄이 주어지고, 원래 이미지와 같은 형식으로 미샤의 프로그램이 출력한 이미지가 묘사됩니다.

미샤의 프로그램이 부정확하게 반전시킨 픽셀의 수를 출력합니다.

>>>코드

n, m = map(int, input().split())
l, r = [], []
p = 0
for i in range(n):
    l.append(input())
input()
for i in range(n):
    r.append(input())
for i in range(n):
    for j in range(m):
        if l[i][j] == r[i][j]:
            p += 1
print(p)
728x90
반응형
728x90
반응형

7/ 01 파이썬 공부
1. 백준 9772 Quadrants
Given the coordinates (x,y) of some points in 2-dimensional plane, find out which quadrant(Q1-Q4) the points are located. If a point is located on X-axis or Y-axis, print out AXIS instead.

Each line contains a pair of real numbers which is the coordinate of a point. 
Input is terminated by 0 0.
Print out in each line Q1, Q2, Q3, Q4 or AXIS for each point.

>>>해석
2차원 평면에서 어떤 점들의 좌표(x,y)가 주어졌을 때, 그 점들이 어느 사분면(Q1-Q4)에 있는지 알아내십시오. 점이 X축이나 Y축에 있으면 대신 AXIS를 출력합니다.

각 라인에는 점의 좌표인 실수 쌍이 포함되어 있습니다.
입력은 0 0으로 종료됩니다.
각 포인트에 대해 Q1, Q2, Q3, Q4 또는 AXIS를 각 줄에 인쇄하십시오.

>>>코드

while True:
    x, y = map(float, input().split())
    if x == 0 and y == 0:
        print('AXIS')
        break
    elif x == 0 or y == 0:
        print('AXIS')
    elif x > 0 and y > 0:
        print('Q1')
    elif x < 0 and y > 0:
        print('Q2')
    elif x < 0 and y < 0:
        print('Q3')
    else:
        print('Q4')



2. 백준 13580 Andando no tempo
Imagine que você tenha uma máquina do tempo que pode ser usada no máximo três vezes, e a cada uso da máquina você pode escolher voltar para o passado ou ir para o futuro. A máquina possui três créditos fixos; cada crédito representa uma certa quantidade de anos, e pode ser usado para ir essa quantidade de anos para o passado ou para o futuro. Você pode fazer uma, duas ou três viagens, e cada um desses três créditos pode ser usado uma vez apenas. Por exemplo, se os créditos forem 5, 12 e 9, você poderia decidir fazer duas viagens: ir 5 anos para o futuro e, depois, voltar 9 anos para o passado. Dessa forma, você terminaria quatro anos no passado, em 2012. Também poderia fazer três viagens, todas indo para o futuro, usando os créditos em qualquer ordem, terminando em 2042.

Neste problema, dados os valores dos três créditos da máquina, seu programa deve dizer se é ou não possível viajar no tempo e voltar para o presente, fazendo pelo menos uma viagem e, no máximo, três viagens; sempre usando cada um dos três créditos no máximo uma vez.

A entrada consiste de uma linha contendo os valores dos três créditos A, B e C.

Restrições
1  ≤ A, B, C ≤ 1000

Seu programa deve imprimir uma linha contendo o caracter “S” se é possível viajar e voltar para o presente, ou “N” caso contrário.

>>>해석
한 번 사용할 때마다 과거로 갈지 미래로 갈지 정할 수 있는 타임머신을 총 세 번까지 쓸 수 있다고 가정합시다. 
타임머신에는 세 개의 고정된 수가 있습니다; 
각 수는 당신이 과거로 또는 미래로 이동할 때 뛰어넘는 햇수를 의미합니다. 
당신은 한 번, 두 번, 또는 세 번의 여행을 할 수 있지만, 세 개의 수는 오직 한 번만 쓰일 수 있습니다. 
예를 들어 세 개의 수가 5, 12, 9면 당신은 다음과 같이 두 번 여행할 수 있습니다: 
5년 뒤의 미래로 갔다가, 그때로부터 9년 전의 과거로 이동하기. 
결과적으로 당신은 4년 전의 과거인 2012년에 있게 될 것입니다. 
만약 당신이 세 개의 수를 어떤 순서로 쓰든 세 번의 여행을 모두 미래로 떠난다면 2042년에 도착하게 됩니다.

이 문제에서 타임머신에 부여된 세 개의 수가 주어졌을 때, 당신의 프로그램은 최소 한 번에서 최대 세 번 시간 여행을 했다가 현재로 되돌아올 수 있는지 판단해야 합니다; 항상 세 개의 수는 최대 한 번만 쓰일 수 있습니다.

한 줄에 세 수 A, B, C가 주어집니다. (1 <= A, B, C <= 1000)
현재로 되돌아올 수 있으면 "S", 아니면 "N"을 출력합니다.

>>>코드

a, b, c = map(int, input().split())
if a == b or b == c or c == a or max(a,b,c) == a + b + c - max(a,b,c):
    print('S')
else:
    print('N')



3. 백준 
O novo prédio da Sociedade Brasileira de Computação (SBC) possui 3 andares. Em determinadas épocas do ano, os funcionários da SBC bebem muito café. Por conta disso, a presidência da SBC decidiu presentear os funcionários com uma nova máquina de expresso. Esta máquina deve ser instalada em um dos 3 andares, mas a instalação deve ser feita de forma que as pessoas não percam muito tempo subindo e descendo escadas.

Cada funcionário da SBC bebe 1 café expresso por dia. Ele precisa ir do andar onde trabalha até o andar onde está a máquina e voltar para seu posto de trabalho. Todo funcionário leva 1 minuto para subir ou descer um andar. Como a SBC se importa muito com a eficiência, ela quer posicionar a máquina de forma a minimizar o tempo total gasto subindo e descendo escadas.

Sua tarefa é ajudar a diretoria a posicionar a máquina de forma a minimizar o tempo total gasto pelos funcionários subindo e descendo escadas.

A entrada consiste em 3 números, A1, A2, A3 (0 ≤ A1, A2, A3 ≤ 1000), um por linha, onde Ai representa o número de pessoas que trabalham no i-ésimo andar.
Seu programa deve imprimir uma única linha, contendo o número total de minutos a serem gastos com o melhor posicionamento possível da máquina.

>>>해석
브라질 컴퓨터 공동체(SBC)의 새 건물은 3층입니다. 특정 기간에 SBC 직원은 엄청난 양의 커피를 마십니다. 따라서 SBC의 회장은 직원에게 새 에스프레소 기계를 선물하기로 했습니다. 기계는 세 층 중 하나에 설치되어야 하는데, 사람이 계단을 오르내리는데 너무 오랜 시간을 소모하지 않도록 설치되어야 합니다.

각 SBC 직원은 하루에 에스프레소 한 잔을 마십니다. 
직원은 자신이 일하는 층에서 기계가 있는 층으로 갔다가 다시 자신이 일하는 층으로 돌아와야 합니다. 
직원이 한 층을 내려가거나 올라가는 데는 1분이 걸립니다. SBC는 효율성에 많은 신경을 쓰고 있기에, 계단을 오르내리는 시간을 최소화하는 방향으로 기계를 배치하려 합니다. 당신의 목표는 이사진을 도와 직원이 계단을 오르내리는 데 드는 시간이 최소가 되도록 기계를 배치하는 것입니다.

입력으로 세 수 A1, A2, A3 (0 <= A1, A2, A3 <= 1000)가 한 줄마다 주어지는데, 
Ai는 i층에서 일하고 있는 사람의 수를 의미합니다.
가장 이상적으로 기계를 배치했을 때 소비되는 총 시간을 한 줄에 출력합니다.

>>>코드

a1 = int(input())
a2 = int(input())
a3 = int(input())
r1 = 2 * a2 + 4 * a3
r2 = 2 * a1 + 2 * a3
r3 = 4 * a1 + 2 * a2
print(min(r1,r2,r3))
728x90
반응형
728x90
반응형

6/ 30 파이썬 공부
1. 백준 8558 Silnia
Niech n będzie nieujemną liczbą całkowitą. Liczbę n! (czytaj n-silnia) definiuje się następująco. Jeśli n ≤ 1, to n! = 1. Dla n > 1, n! jest równe iloczynowi wszystkich liczb od 1 do n, czyli n! = 1 * 2 * ... * n. Na przykład 4! = 1 * 2 * 3 * 4 = 24.
Napisz program, który

- wczyta ze standardowego wejścia nieujemną liczbę całkowitą n,
- policzy cyfrę jedności w zapisie dziesiętnym liczby n!,
- wypisze wynik na standardowe wyjście.

Pierwszy i jedyny wiersz standardowego wejścia zawiera dokładnie jedną nieujemną liczbę całkowitą n, 0 ≤ n ≤ 30 000.

W pierszym i jedynym wierszu standardowego wyjścia Twój program powinien zapisać dokładnie jedną cyfrę równą cyfrze jedności w zapisie dziesiętnym liczby n!.

(이게 무슨 언어지 진짜...)

>>>해석
음이 아닌 정수 n이 있습니다. (n 팩토리얼이라 읽는) n!은 다음과 같이 정의합니다. 
n <= 1이면 n! = 1입니다. n > 1일 경우, n!은 1부터 n까지의 곱과 같아 n! = 1 * 2 * ... * n입니다. 
예를 들어, 4! = 1 * 2 * 3 * 4 = 24입니다.

아래의 조건을 만족하는 프로그램을 작성합시다.

- 표준 입력으로 음이 아닌 정수 n을 입력 받는다.
- n!의 십진수 표기에서 일의 자리 수를 저장한다.
- 그 값을 표준 출력에 표시한다.

유일한 줄에 0 <= n <= 30000인 음이 아닌 정수 n이 주어집니다.
유일한 줄에 n!의 십진법 표기에서 일의 자리 수를 나타내는 한 자리를 출력합니다.

>>>코드

n = int(input())
r = 1
for i in range(n):
    r = r*(i+1)
print(r%10)



2. 백준 8723 Payyki
Bajtuś znalazł w lesie 3 patyki. Teraz chciałby wiedzieć, czy może z nich zbudować trójkąt prostokątny lub równoboczny. Bajtuś nie może łamać patyków, może je wykorzystać tylko w całości.

Pierwszy wiersz wejścia zawiera trzy liczby całkowite a, b, c (1 ≤ a, b, c ≤ 1000), oznaczające odpowiednio długości pierwszego, drugiego i trzeciego patyka.

Pierwszy i jedyny wiersz wyjścia powinien zawierać jedną liczbę: 0 - jeśli Bajtuś nie może zbudować, ani trójkąta prostokątnego ani równobocznego, 1 - jeśli Bajtuś może zbudować tylko trójkąt prostokątny, 2 - jeśli Bajtuś może zbudować tylko trójkąt równoboczny,

(이게 무슨 언어지22)

>>>해석
바이투스는 숲에서 막대기 3개를 발견했습니다. 그는 막대기로 직각삼각형이나 정삼각형을 만들 수 있는지 궁금합니다. 바이투스는 막대기를 부러뜨릴 수 없으며, 그대로만 사용할 수 있습니다.

첫 줄에 각각 첫 번째 막대, 두 번째 막대, 세 번째 막대의 길이를 나타내는 세 정수 a, b, c (1 <= a, b, c <= 1000)가 주어집니다.

오로지 한 줄에 하나의 숫자를 출력합니다: 바이투스가 직각삼각형이나 정삼각형을 만들 수 없다면 0, 직각삼각형만 만들 수 있다면 1, 정삼각형만 만들 수 있다면 2를 출력합니다.

>>>코드

l = list(map(int, input().split()))
l.sort()
if l[0] == l[1] and l[1] == l[2]:
    print(2)
elif l[2]**2 == l[0]**2 + l[1]**2:
    print(1)
else:
    print(0)



3. 백준 8760 Schronisko
Kiedy Hektor zajmował się realizacją projektu HektorJudge, jego kolega Wiktor uznał, że życie nie powinno składać się wyłącznie z siedzenia przy komputerze i wybrał się na wycieczkę w góry. Kiedy wieczorem dotarł do schroniska ze zdziwieniem odkrył, że nie tylko on wpadł na pomysł spędzenia weekendu w górach - schronisko było pełne turystów!

W tej kryzysowej sytuacji kierownik schroniska był zmuszony zorganizować turystom nocleg na podłodze w głównej sali schroniska. Sala ma postać prostokąta złożonego z W*K kwadratowych pól ułożonych w prostokąt o wymiarach W wierszy na K kolumn. Każdy turysta zajmuje dokładnie dwa sąsiednie (albo w pionie albo w poziomie) pola. Ile turystów można maksymalnie ułożyć w sali o zadanych wymiarach tak, aby każde pole było zajęte maksymalnie przez jednego turystę? Wiktor, jako matematyk-informatyk natychmiast obliczył prawidłowy wynik.

W pierwszej linii znajduje się liczba naturalna Z ( 1 <= Z <= 10 ) oznaczająca liczbę zestawów testowych. Następnie opisywane są kolejne zestawy.
Opis pojedynczego zestawu testowego składa się z jednej linii zawierającej dwie oddzielone pojedynczą spacją dodatnie całkowite W i K (1 <= W, K <= 1000).

Dla każdego zestawu testowego należy w osobnej linii wypisać maksymalną liczbę turystów którzy mogą jednocześnie przenocować w sali schroniska. Kolejność wypisywanych odpowiedzi musi odpowiadać kolejności zestawów na wejściu.

(이게 무슨 언어지333)

>>>해석
헥토르가 HektorJudge 프로젝트를 하는 동안, 동료 빅토르는 컴퓨터 앞에만 앉아 있기에는 인생이 아깝다 생각해 등산 여행을 갔습니다. 저녁에 대피소에 도착한 후, 그는 주말을 산에서 보내겠다는 생각을 한 게 자신만이 아니라는 것에 놀랐습니다 - 대피소는 여행객으로 가득 차 있었습니다!

예기치 못한 상황이 닥치자, 대피소 관리자는 하루 동안 여행객을 대피소 본관에 질서 있게 배정하는 임무를 맡게 됐습니다. 본관은 정사각형 모양의 구역이 W개의 열과 K개의 행을 이루는 W * K 크기의 직사각형 공간입니다. 각 여행객은 (가로든 세로든) 인접한 두 구역을 차지합니다. 본관의 크기가 주어지고 한 구역을 최대 한 명의 여행객에 배정한다고 할 때, 최대 몇 명의 여행객을 본관에 배정할 수 있습니까? 컴퓨터 과학자이자 수학자인 빅토르는 단숨에 정확한 답을 도출했습니다.

테스트 케이스의 수를 나타내는 자연수 Z (1 <= Z <= 10)가 첫 줄에 주어집니다. 
이후 테스트 케이스가 묘사됩니다.
한 줄의 테스트 케이스에 두 양의 정수 W, K(1 <= W, K <= 1000)가 하나의 공백을 두고 주어집니다.

각 테스트 케이스에 대해, 하루 동안 동시에 본관에 머무를 수 있는 최대 여행객의 수를 별개의 줄에 출력합니다. 입력에 주어진 테스트 케이스의 순서에 맞춰 출력해야 합니다.

>>>코드

for _ in range(int(input())):
    w, k = map(int, input().split())
    print(w*k//2)



4. 백준 10480 Oddities
Some numbers are just, well, odd. For example, the number 3 is odd, because it is not a multiple of two. Numbers that are a multiple of two are not odd, they are even. More precisely, if a number n can be expressed as n = 2 ∗ k for some integer k, then n is even. For example, 6 = 2 ∗ 3 is even.
Some people get confused about whether numbers are odd or even. To see a common example, do an internet search for the query “is zero even or odd?” (Don’t search for this now! You have a problem to solve!)
Write a program to help these confused people.

Input begins with an integer 1 ≤ n ≤ 20 on a line by itself, indicating the number of test cases that follow. Each of the following n lines contain a test case consisting of a single integer −10 ≤ x ≤ 10.

For each x, print either ‘x is odd’ or ‘x is even’ depending on whether x is odd or even.

>>>해석
어떤 수들은 한 마디로 홀로 남았습니다. 예를 들어 3은 홀로 남은 수인데, 2의 배수가 아니기 때문입니다. 
2의 배수는 홀로 남은 수가 아닌 짝수입니다. 
정확하게 말하면, 만약 숫자 n이 어떤 정수 k에 대해 n = 2 * k로 표현될 수 있다면, n은 짝수입니다. 
예를 들어, 6 = 2 * 3이므로 짝수입니다.
몇몇 사람들은 수가 홀수인지 짝수인지 헷갈려 합니다. 
그 예시로, 인터넷에 질문 "0이 짝수인가요, 홀수인가요?"를 검색해봅시다. 
(지금은 검색하지 마세요! 풀어야 하는 문제가 있습니다!)
이렇게 헷갈리는 사람들을 돕는 프로그램을 작성합시다.

입력은 이후 나올 테스트 케이스의 수를 나타내는 하나의 정수 1 <= n <= 20으로 시작됩니다. 이후 n개의 줄에 -10 <= x <= 10으로 나타낸 테스트 케이스가 주어집니다.
각 x에 대해, x가 홀수인지 짝수인지 판별해 'x is odd' 또는 'x is even'을 출력합니다.

>>>코드

for _ in range(int(input())):
    n = int(input())
    if n%2 == 0:
        print('%d is even' %(n))
    else:
        print('%d is odd' %(n))



5. 백준 8674 Tabliczka
Mama przyniosła Piotrusiowi i Pawełkowi tabliczkę czekolady o wymiarach a i b. Chłopcy chcą podzielić tabliczkę za pomocą jednego prostego łamania, wzdłuż kostek pionowych lub poziomych. Chłopcy chcą podzielić tabliczkę jak najbardziej sprawiedliwie, czyli tak, aby różnica pomiędzy kawałkami, które przypadną na każdego z nich, była jak najmniejsza.

W pierwszym i jedynym wierszu wejścia znajdują się dwie liczby całkowite a, b (1 ≤ a, b ≤ 232), oznaczające odpowiednio liczbę kostek znajdujących się w każdym wierszu oraz każdej kolumnie tabliczki czekolady.

W pierwszym i jedynym wierszu wyjścia powinna się znaleźć jedna liczba całkowita, równa różnicy pomiędzy kawałkami, które dostaną chłopcy.

>>>해석
엄마가 피오트르쇼비와 파벨코비에게 a * b개의 칸으로 이루어진 초콜릿 바를 사줬습니다. 
아이들은 가로 줄이나 세로 줄에 맞춰 딱 한 번 초콜릿 바를 잘라 나누려고 합니다. 아이들은 최대한 공평하게, 달리 말해 두 명이 갖는 초콜릿 바의 크기의 차가 최소가 되도록 초콜릿 바를 나누려고 합니다.

한 줄에 각각 초콜릿 바의 열과 행에 있는 칸의 수를 나타내는 a, b (1 <= a, b <= 2^32)가 주어집니다. 
딱 한 줄에 두 아이가 받는 초콜릿 바 조각의 크기의 차를 나타내는 정수를 출력합니다.

>>>코드

a, b = map(int, input().split())
if a%2 == 0 or b%2 == 0:
    print(0)
else:
    print(min(a,b))



6. 백준 18411 試験 (Exam)
JOI 君は情報の試験を 3 回受けた.試験の点数はすべて 0 以上 100 以下の整数である.
JOI 君の成績は 3 回の試験の点数のうち高い方から 2 つを足し合わせた合計によって決まる.
3 回の試験の点数 A, B, C が与えられたとき,3 回の試験の点数のうち高い方から 2 つを足し合わせた合計を出力するプログラムを作成せよ.

入力は以下の形式で標準入力から与えられる.

A B C

3 回の試験の点数のうち高い方から 2 つを足し合わせた合計を 1 行で出力せよ.

>>>해석
JOI 군은 정보 시험을 3번 봤습니다. 시험 점수는 전부 0 이상 100 이하의 정수입니다.
JOI 군의 성적은 3회 시험 점수 중 가장 높은 두 개를 합한 값입니다.
3회의 시험 점수 A, B, C가 주어질 때, 3회 시험의 점수 중 높은 두 개를 더한 합계를 출력하는 프로그램을 작성합시다.

이하와 같이 표준 입력이 주어집니다. 

A B C

3회 시험 점수 중 높은 2개를 더한 값을 한 줄에 출력합니다.

>>>코드

a, b, c = map(int, input().split())
print(a+b+c-min(a,b,c))



7. 백준 15474 鉛筆 (Pencils)
JOI 君は鉛筆を N 本買うために近くの文房具店に行くことにした.
文房具店では鉛筆が一定の本数ずつのセットで売られている.
セット X は A 本で B 円,セット Y は C 本で D 円である.
JOI 君はセット X かセット Y の一方を選び,選んだセットをいくつか購入する.両方のセットを購入することはできない.
N 本以上の鉛筆を得るために必要な金額の最小値を求めよ.

入力は以下の形式で標準入力から与えられる.

N A B C D

JOI 君が N 本以上の鉛筆を手に入れるのに必要な金額の最小値を出力せよ.

>>>해석
JOI 군은 연필을 N개 사기 위해 가까운 문방구에 가기로 했습니다.
문방구에서는 연필을 일정 개수를 묶은 세트로 판매하고 있습니다. 
세트 X는 연필 A개로 이루어져 B엔, 세트 Y는 연필 C개로 이루어져 D엔입니다.
JOI 군은 세트 X와 세트 Y 중 하나를 골라, 고른 세트를 몇 개 구매합니다. 
양쪽의 세트를 모두 구입하는 것은 불가능합니다. 
N개 이상의 연필을 갖기 위해 필요한 금액의 최솟값을 구합시다.

아래의 형식으로 표준 입력이 주어집니다.

N A B C D

JOI 군이 N개 이상의 연필을 사기 위해 필요한 금액의 최솟값을 출력합니다.

>>>코드

n, a, b, c, d = map(int, input().split())
if n%a == 0:
    price1 = n//a * b
else:
    price1 = (n//a +1) * b
if n%c == 0:
    price2 = n//c * d
else:
    price2 = (n//c +1) * d
print(min(price1, price2))



8. 백준 8710 Koszykarz
Kozik pragnie zostać koszykarzem. Po rozmowie z trenerem okazało się, że jest za niski. Kozik jest jednak tak zdeterminowany, że chce spełnić wymagania trenera, nawet jeśli okazałoby się to oszustwem. Wpadł więc na genialny pomysł robienia sobie guzów na głowie, aż osiągnie wymagany wzrost. Zauważył, że przy każdym uderzeniu guz się powiększa o m cm. Kozik zastanawia się ile minimalnie razy będzie musiał się uderzyć.

W pierwszej linii wejścia 3 liczby całkowite: k, w, m (1 ≤ k ≤ 200, 1 ≤ w, m ≤ 109), oznaczające odpowiednio wysokość Kozika, wymaganą przez trenera wysokość oraz wartość powiększania się guza po każdym uderzeniu.

Pierwszy i jedyny wiersz wyjścia powinien zawierać jedną liczbę całkowitą równą minimalnej liczbie uderzeń, które musi wykonać Kozik.

>>>해석
코직은 농구 선수가 꿈입니다. 하지만 코치에게 얘기를 하니 키가 너무 작다는 얘기를 들었습니다. 
하지만 코직은 열정으로 가득했으므로 편법을 쓰더라도 코치의 요구 조건을 맞추려 합니다. 
코직은 원하는 키가 될 때까지 머리에 혹을 만든다는 엄청난 아이디어를 떠올렸습니다. 
그는 한 번 때릴 때마다, 혹이 m cm씩 자란다는 것을 발견했습니다. 
코직은 자기를 최소 얼마나 때려야 할지 궁금합니다.

한 줄에 각각 코직의 키, 코치가 요구한 키, 한 번 때릴 때마다 늘어나는 혹의 길이를 나타내는 세 정수 k, w, m (1 <= k <= 200, 1 <= w, m <= 10 ^ 9)가 주어집니다.

오로지 한 줄에 코직이 스스로를 때려야 하는 최소 횟수를 나타낸 하나의 정수를 출력합니다. 

>>>코드

k, w, m = map(int, input().split())
if (w-k)%m == 0:
    print((w-k)//m)
else:
    print((w-k)//m + 1)



9. 백준 18408 3 つの整数 (Three Integers)
3 つの整数 A, B, C が与えられる.A, B, C はそれぞれ 1 または 2 である.1 と 2 のうち,どちらが多くあるか.

入力は以下の形式で標準入力から与えられる.

A B C

1 と 2 のうち,個数が多い方を出力せよ.

>>>해석
세 정수 A, B, C가 주어집니다. A, B, C는 각각 1 또는 2입니다. 1과 2 중, 더 많은 것은 무엇입니까.

아래와 같은 형식으로 표준 입력이 주어집니다.

A B C

1과 2 중, 더 많은 쪽을 출력합니다.

>>>코드

l = list(map(int, input().split()))
if l.count(1)>l.count(2):
    print(1)
else:
    print(2)



10. 백준 24075 計算 (Calculation)
2 つの整数 A, B が与えられる.A+B, A-B の中で最大の値と最小の値を順に出力せよ.

入力は以下の形式で標準入力から与えられる.

A B

出力は 2 行からなる.
1 行目に,A+B, A-B の中で最大の値を出力せよ.
2 行目に,A+B, A-B の中で最小の値を出力せよ.

>>>해석
2개의 정수 A, B가 주어집니다. A+B, A-B 중 최댓값과 최솟값을 순서대로 출력합시다.

아래의 형식으로 표준 입력이 주어집니다.

A B

출력은 두 줄입니다.
첫째 줄에는, A+B, A-B 중 최댓값을 출력합니다.
둘째 줄에는, A+B, A-B 중 최솟값을 출력합니다.

>>>코드

a, b = map(int, input().split())
print(max(a+b, a-b))
print(min(a+b, a-b))
728x90
반응형
728x90
반응형

6/ 29 파이썬 공부
1. 백준 26592 Triangle Height
Your Math teacher asked you to write a program to help him generate homework solutions. 
The program will need to find the height of a triangle given its area and its base length.

Formula:
a = (h*b)/2 (a – area, b – base length, h – height)

The first line will contain a single integer n that indicates the number of lines that follow. Each line will include the area and base length of a triangle with the two values separated by a single space.

area base

For each input display the height of the triangle with 2 decimal places, in the following format:

The height of the triangle is #.## units

>>>해석
수학 선생님이 숙제 해설을 생성하는 데 도움이 되는 프로그램을 작성하라고 요청했습니다.
프로그램은 삼각형의 넓이와 밑변 길이가 주어진 삼각형의 높이를 찾아야 합니다.

공식:
a = (h*b)/2 (a – 면적, b – 밑면 길이, h – 높이)

첫 번째 줄에는 테스트 케이스의 개수 n이 입력됩니다. 
각 선에는 하나의 공백으로 구분된 두 값이 있는 삼각형의 면적과 기본 길이가 포함됩니다.

면적 밑면 길이

각 입력에 대해 다음 형식으로 소수점 이하 2자리까지 삼각형의 높이를 표시합니다.

The height of the triangle is #.## units

>>>코드

for _ in range(int(input())):
    a, b = map(float, input().split())
    print('The height of the triangle is %.2f units' %(2*a/b))



2. 백준 26340 Fold the Paper Nicely
Dr. Orooji has a daily calendar (365 pages) on his desk. Every morning, he tears off one page and, as he is reading the notes on the next page, he folds (out of habit) the sheet in his hand. Dr. O noticed that he always folds the sheet (a rectangular paper) along the longer side, e.g., if one side is 80 and the other side is 60, he would fold along 80; this will make the paper of size 40 and 60; if he folds it again, he would fold along 60 since that’s the longer side now.

Given a rectangular piece of paper and how many times Dr. O folds it, you are to determine the final sizes. When folding a side with an odd length, the fraction is ignored after folding, e.g., if a side is 7, it will become 3 after folding.

The first input line contains a positive integer, n, indicating the number of data sets. The sets are on the following n input lines, one set per line. Each set contains three positive integers (each ≤ 10000), the first two providing the rectangle sides and the third providing the number of folds.

At the beginning of each test case, output “Data set: v” where v is the input values. Then, on the next output line, print the final values for the rectangle (larger side of the final values first). Leave a blank line after the output for each test case. Follow the format illustrated in Sample Output.

>>>해석
Orooji 박사의 책상에는 일력(365페이지)이 있습니다. 매일 아침 Orooji 박사는 일력을 한 페이지 찢고 다음 페이지에 써둔 메모를 읽으면서 찢은 페이지를 접는 습관이 있습니다. Orooji 박사는 자신이 항상 긴 쪽을 따라 직사각형으로 찢은 일력을 접는다는 것을 알아차렸습니다. 예를 들어, 한 변이 80이고 다른 변이 60이라면 80인 변을 접어 접은 이후 종이의 크기는 40과 60이 될 것입니다. 
한 번 더 접게 된다면 더 긴 변이 된 60인 부분을 따라 접을 것입니다.
직사각형의 종이 조각과 Orooji 박사가 접는 횟수가 주어지면 접은 후의 최종 크기를 구해야 합니다. 
홀수 길이의 변을 접게 된다면 소수부는 무시됩니다. 
예를 들어 길이가 7인 변을 따라 접는다면 접은 후의 길이는 3이 됩니다.

첫째 줄에는 테스트 케이스의 개수가 양의 정수 n으로 주어집니다. 각각의 테스트 케이스는 n개의 줄에 걸쳐 주어지며, 한 줄에 하나의 테스트 케이스가 주어집니다.
각 줄에는 3개의 양의 정수 (각각≤ 10000)가 포함되며, 처음 두 정수는 직사각형의 각 변의 길이, 세번째 정수는 접는 횟수를 나타냅니다.

각 테스트 케이스는 "Data set: v"로 시작합니다. 여기서 v는 테스트 케이스의 입력값입니다.
그 다음줄에 사각형의 두 변의 길이를 길이가  긴 것부터 순서대로 출력합니다. 
각 테스트케이스가 끝나면 빈 출을 출력합니다. 예제 출력과 동일한 형식으로 출력해야합니다.
길이는 항상 정수의 형태이다.

>>>코드

for _ in range(int(input())):
    l = list(map(int, input().split()))
    e1, e2 = l[0], l[1]
    for i in range(l[2]):
        if e1>e2:
            e1 = e1//2
        else:
            e2 = e2//2
    print('Data set:', *l)
    print('%d %d\n' %(max(e1, e2), min(e1, e2)))



3. 백준 25895 Majestic 10
The movie “Magnificent 7” has become a western classic. Well, this year we have 10 coaches training the UCF programming teams and once you meet them, you’ll realize why they are called the “Majestic 10”! The number 10 is actually special in many different ways. For example, in basketball, they keep track of various statistics (points scored, rebounds, etc.) and if a player has 10+ (10 or more) in a particular stat, they call it a double.
Given three stats for a basketball player, you are to determine how many doubles the player has, i.e., how many of the stats are greater than or equal to 10.

The first input line contains a positive integer, n, indicating the number of players. Each of the following n input lines contains three integers (separated by a space and each between 0 and 100, inclusive), providing the three stats for a player.

Print each input line as it appears in the input. Then, on the following output line, print a message indicating how many stats are greater than or equal to 10:

- print zilch if none of the three stats is greater than or equal to 10,
- print double if one of the three stats is greater than or equal to 10,
- print double-double if two of the three stats are greater than or equal to 10,
- print triple-double if all three stats are greater than or equal to 10.

Leave a blank line after the output for each player.

>>>해석
영화 '매그니피센트 7'은 서부극의 고전이 됐다. 
올해 우리에게는 UCF 프로그래밍 팀을 훈련하는 10명의 코치가 있습니다. 
일단 그들을 만나보면 그들이 "마제스틱 10"이라고 불리는 이유를 알게 될 것입니다! 
숫자 10은 사실 여러 면에서 특별합니다. 예를 들어, 농구에서는 다양한 통계(득점, 리바운드 등)를 추적하고 특정 통계에서 선수가 10+(10 이상)이면 이를 더블이라고 부릅니다.

농구 선수에 대한 세 가지 통계가 주어지면 플레이어가 얼마나 많은 더블을 가지고 있는지, 즉 얼마나 많은 통계가 10보다 크거나 같은지 결정해야 합니다.

첫째 줄에 플레이어 수를 나타내는 양의 정수 n이 주어집니다. 다음 n개의 줄에 플레이어에 대한 세 가지 통계를 제공하는 0 이상 100 이하의 세 개의 정수가 공백으로 구분되어 주어집니다.

우선 입력에 주어지는 통계를 출력합니다. 그 후, 더블에 대한 메시지를 출력합니다.

- 세 통계 중 어느 것도 10보다 크거나 같지 않으면 zilch를 출력
- 세 통계 중 하나가 10보다 크거나 같으면 double을 출력
- 세 통계 중 두 통계가 10보다 크거나 같으면 double-double을 출력
- 세 통계가 모두 10보다 크거나 같으면 triple-double을 출력

각 플레이어의 출력 뒤에 빈 줄을 출력합니다.

>>>코드

for _ in range(int(input())):
    l = list(map(int, input().split()))
    r = 0
    for i in l:
        if i >= 10:
            r += 1
    print(*l)
    if r == 0:
        print('zilch\n')
    elif r == 1:
        print('double\n')
    elif r == 2:
        print('double-double\n')
    else:
        print('triple-double\n')
728x90
반응형
728x90
반응형

6/ 28 파이썬 공부
1. 백준 26530 Shipping
Your animals have begun producing products, and you’re honestly a little strapped for cash. Since you have far more animal byproducts than you know what to do with, you’ve decided to begin shipping them for extra money. Given the information in your shipping ledger, determine how much money you can expect to make.

The first line will contain a single integer n that indicates the number of data sets that follow. Each data set will start with a single integer x denoting how many items follow. The next x lines consist of a string, and integer, and a floating point number to two decimal places, representing the name of what was sold, the quantity, and the unit price of each item.

For each test case, output the amount of money you expect to make with all of the goods you sold, rounded to two decimal places.

>>>해석
당신의 동물은 제품을 생산하기 시작했으며 솔직히 현금이 약간 부족합니다. 
당신은 당신이 필요한 양의 동물 부산물보다 훨씬 더 많은 동물 부산물이 있기 때문에 부 수입을 벌기 위해 배송을 시작하기로 결정했습니다. 배송 장부의 정보를 바탕으로 얼마나 많은 돈을 벌 수 있는지 결정하십시오.

첫 번째 줄에는 다음 데이터 세트의 수를 나타내는 단일 정수 n이 포함됩니다. 
각 데이터 세트는 뒤에 오는 항목 수를 나타내는 단일 정수 x로 시작합니다. 
다음 x 행은 문자열, 정수, 소수점 이하 두 자리까지의 부동 소수점 숫자로 구성되며 판매된 항목의 이름, 수량 및 각 항목의 단가를 나타냅니다.
각 테스트 케이스에 대해 판매한 모든 상품으로 예상되는 금액을 소수점 둘째 자리까지 반올림하여 출력하십시오.

>>>코드

for _ in range(int(input())):
    result = 0
    for i in range(int(input())):
        name, count, price = input().split()
        result += float(count) * float(price)
    print('$%.2f' %(result))



2. 백준 26350 Good Coin Denomination
Different countries use different coin denominations. For example, the USA uses 1, 5, 10, and 25. A desirable property of coin denominations is to have each coin at least twice the amount of its previous coin in sorted order. For example, the USA denominations have this property, but the coin denominations {1, 5, 6} do not (6 is not at least twice 5).
Given the coin denominations, you are to determine if the set has the above property.

The first input line contains a positive integer, n, indicating the number of denomination sets to check. The sets are on the following n input lines, one set per line. Each set starts with an integer d (1 ≤ d ≤ 10), which is a count of various coin amounts in the set; this is followed by d distinct positive integers (each less than 1,000) giving each coin amount (assume the coin amounts are given in increasing order).

At the beginning of each test case, output “Denominations: v” where v is the input values. Then, on the next output line, print a message indicating whether or not the set has the above property. Leave a blank line after the output for each test case. Follow the format illustrated in Sample Output.

>>>해석
나라마다 다른 액면가를 사용합니다. 예를 들어 미국은 1,5,10,25를 사용합니다. 
액면가는 각 동전이 작은 것부터 순서대로 이전 크기의 액면가보다 두 배 이상의 양을 가지는 것이 적합합니다. 
미국의 액면가는 이 속성을 만족하지만, {1,5,6}은 이 속성을 만족하지 않습니다. 
(6은 5의 두 배 보다 작기 때문입니다)
액면가가 주어지면 그 액면가가 위의 속성을 만족하는 지 확인해야합니다.

첫번째 줄에는 테스트 케이스의 개수가 양의 정수 n으로 주어집니다. 
각 테스트 케이스는 n개의 줄에 걸쳐 한 줄에 하나씩 주어집니다. 
각 테스트 케이스는 정수d(1 ≤ d ≤ 10)로 시작하며, 이는 액면가가 주어질 동전의 종류입니다. 
그 다음에는 각 동전의 액면가가 d개의 양의 정수로 주어집니다(각각 1000 미만). 
동전의 액면가는 오름차순으로 주어집니다.

각 테스트 케이스는 "Denominations: v"로 시작합니다. 여기서 v는 입력된 액면가들입니다. 
다음 줄에 위 속성을 만족하는 지 여부를 나타내는 메시지를 출력합니다. 
각 테스트 케이스가 끝나면 빈 줄을 하나 출력합니다. 기타 설명되지 않은 출력형식은 예제출력을 따릅니다.

>>>코드

for _ in range(int(input())):
    l = list(map(int, input().split()))
    c = 0
    for i in range(1, len(l)-1):
        if l[i] * 2 > l[i+1]:
            c = 1
    if c == 0:
        print('Denominations:',*l[1::])
        print('Good coin denominations!\n')
    else:
        print('Denominations:',*l[1::])
        print('Bad coin denominations!\n')



3. 백준 25881 Electric Bill
To encourage customers to conserve energy (and protect the environment), the electric companies typically have a lower rate for the first 1000 kilowatt-hour (KWH) of electric usage and a higher rate for the additional usage (KWH is a derived unit of energy equal to 3.6 megajoules).
Given the rate (per KWH) for the first 1000 KWH usage, the rate (per KWH) for the additional usage, and a customer’s energy consumption, you are to determine the charges (bill) for the customer.

The first input line contains two integers (each between 2 and 20, inclusive), indicating the rate/KWH for the first 1000 KWH and the rate/KWH for the additional usage, respectively. The next input line contains a positive integer, n, indicating the number of customers to process. Each of the following n input lines contains an integer (between 1 and 50000, inclusive), indicating a customer’s energy consumption.
For each customer, print the energy consumption, followed by a space, followed by the charges.

>>>해석
고객이 에너지를 절약하고 환경을 보호하도록 장려하기 위해, 전기 회사는 일반적으로 처음 1000 KWH의 전기 사용량에 대해 더 낮은 요율을 적용하고 추가 사용량에 대해 더 높은 요율을 적용합니다.
(KWH는 에너지의 파생 단위입니다. 3.6메가줄과 같음).
처음 1000KWH 사용량에 대한 요율(KWH당), 추가 사용량에 대한 요율(KWH당) 및 고객의 에너지 소비량이 주어질 때, 고객에 대한 요금(청구서)을 결정해야 합니다.

첫째 줄에 2 이상 20 이하의 두 개의 정수가 주어집니다.
각각 처음 1000KWH에 대한 KWH당 요율과 추가 사용량에 대한 KWH당 요율을 나타냅니다.
둘째 줄에는 처리할 고객 수를 나타내는 양의 정수 n이 포함됩니다. 
다음 n개의 줄에는 각각 고객의 에너지 소비량을 나타내는 1 이상 50000 이하의 정수가 주어집니다.
n개의 줄에 걸쳐 각 고객의 에너지 소비량과 요금을 공백으로 구분하여 출력합니다.

>>>코드

a, b = map(int, input().split())
for _ in range(int(input())):
    n = int(input())
    if n <= 1000:
        print(n, a*n)
    else:
        print(n, a*1000 + b*(n-1000))
728x90
반응형
728x90
반응형

6/ 27 파이썬 공부
1. 백준 11121 Communication Channels
Classical information theory is based on the concept of a communication channel.
Information theory is generally considered to have been founded in 1948 by Claude Shannon in his seminal work, “A Mathematical Theory of Communication.” The central paradigm of classical information theory is the engineering problem of the transmission of information over a noisy channel.

http://en.wikipedia.org/wiki/Information theory

In this problem, we will specifically consider one of the simplest possible noisy channels, namely the binary symmetric channel (BSC). A BSC transmits a sequence of bits, but each transmitted bit has a probability p of being flipped to the wrong bit. This is called the crossover probability, as can be understood from the figure. We assume independent behaviour on different bits, so a communication of l bits has probability (1 − p)l of being transmitted correctly. Note that one can always assume that p < 1/2, since a channel with p = 1/2 is totally useless, and a channel with p > 1/2 can easily be transformed to a new channel having crossover probability 1 − p by just flipping all bits of the output.

Of course, it is still possible to communicate over a noisy channel. (In fact, you are doing it all the time!) To be able to do this, one has to add extra bits in order for the receiver to detect or even possibly correct errors. Example implementations of such a feature are parity bits, Cyclic Redundancy Checks (CRC) and Golay codes. These are not relevant to this problem, however, so they will not be discussed here.
In this problem you must investigate the behaviour of a binary symmetric channel.

The first line of the input consists of a single number T, the number of transmissions. Then follow T lines with the input and the output of each transmission as binary strings, separated by a single space.

- 0 < T ≤ 100
- All inputs and outputs has length less than 120.
- T is encoded in decimal.

For each transmission, output OK if the communication was transmitted correctly, or ERROR if it was transmitted incorrectly.

>>>해석
고전 정보 이론은 통신 채널 개념을 기반으로 합니다.

정보 이론은 1948년 클로드 섀넌의 걸작 "통신의 수학 이론"에서 시작됐다고 여겨집니다. 
고전 정보 이론의 핵심 주제는 번잡한 채널에서의 정보 전송에 관한 공학적 문제입니다. 

http://en.wikipedia.org/wiki/Information theory

이 문제는 번잡한 채널 중 가장 단순한 채널 중 하나, 즉 이진 대칭 채널(BSC)을 다룹니다. 
BSC는 비트 값을 전송하는데, 각 비트는 p의 확률로 잘못된 비트로 전송될 가능성이 있습니다. 
이를 교차 확률이라 합니다. 서로 다른 비트의 전송은 독립 시행으로 가정하며, 따라서 소통 중 I개의 비트가 올바르게 전송될 확률은 (1 - p)I입니다. p = 1/2인 채널은 아무 의미가 없고, p > 1/2인 채널은 출력의 모든 비트를 거꾸로 함으로써 교차 확률이 1 - p인 새 채널로 쉽게 변형할 수 있으므로 p < 1/2라 가정해도 무방합니다. 

물론 번잡한 채널에서의 소통은 언제나 가능합니다. (실제로 항상 이용하고 있고요!) 
보통 소통을 위해서는, 수신자가 오류를 탐지하고 잡아낼 수 있도록 메시지에 추가 비트를 더합니다. 
패리티 비트, 순환 중복 검사 (CRC), 골레 부호 등이 그 예시입니다. 
하지만 이는 문제와 무관하므로 여기서 다루지는 않겠습니다.
이 문제에서 당신은 이진 대칭 채널의 상태를 점검해야 합니다.

첫 줄에 전송 수 T가 주어집니다. 
이후 T개의 줄에 이진 문자열인 각 전송의 입력 값과 출력 값이 하나의 공백으로 구분되어 주어집니다. 

- 0 < T <= 100
- 모든 입력 값과 출력 값의 길이는 120보다 작습니다.
- T는 십진수입니다.

각 전송에 대해 소통이 정확했으면 OK를, 부정확했으면 ERROR를 출력합니다.

>>>코드

for _ in range(int(input())):
    a, b = input().split()
    if a == b:
        print('OK')
    else:
        print('ERROR')



2. 백준 27182 Rain Diary
Petya lives in Saint Petersburg and he is keen on meteorology. It is widely believed that it constantly rains in Saint Petersburg. Petya has decided to statistically prove or disprove this statement. For this Petya started a rain diary and every week at Sunday he makes a record, whether it is rainy or not. Petya signs every record with a number of current day in a month, days in a month are numerated from 1 to number of days in the current month (from 28 to 31 in a different monthes).

Today Petya opened his diary and realized, that he made the last record two weeks ago and forgot to make a record last Sunday. Petya remembers, that there was a heavy rain a week ago. He decided to make two records: for today and for the last Sunday. He knows the number of the current day n and sees the number m in the two weeks ago record. What is the number Petya should sign his record for the last Sunday?

The first line of the input contains two integers n and m (1 <= n, m <= 31) --- the number of the current day of the month and the number that the record was signed two weeks ago.
Output a single number -- what number should the record be signed for the last Sunday.

>>>해석
오늘은 일요일이고, 날짜는 n 일이다. 저저번주 일요일의 날짜는 m 일이다. 
그렇다면 저번주 일요일의 날짜는 며칠일까?
한 달은 28, 29, 30, 31 일 중 하나이다. 

첫 번째 줄에 n, m(1 <= n, m <= 31) 이 주어진다.
첫 번째 줄에 저번주 일요일이 며칠인지를 출력한다.

>>>코드

n, m = map(int, input().split())
if n-7 > 0:
    print(n-7)
else:
    print(m+7)



3. 백준 26561 Population
In Emily’s country it is estimated that a person dies every 7 seconds, and a person is born every 4 seconds. Given a beginning population, estimate the population after a certain period of time.

The first line of input will contain a single integer n that indicates the number of lines to follow. Each line will consist of two integers, p and t, where p is the beginning population, and t is the amount of time that will pass. Both p and t will be between the number 1 and 2,000,000,000.
Output the estimated population after the period of time based on the above statistics.

>>>해석
에밀리의 나라에서는 7초마다 한 사람이 죽고 4초마다 한 사람이 태어난다고 추산됩니다. 
초기 인구 수가 주어지면 일정 기간 이후의 인구 수를 구하는 코드를 짜자.

입력의 첫 번째 줄에는 테스트 케이스의 수를 나타내는 정수 n이 입력됩니다. 
각 라인은 p와 t라는 두 개의 정수로 구성됩니다. 여기서 p는 초기 인구수이고 t는 시간입니다. 
p와 t는 모두 1과 2,000,000,000 사이의 숫자입니다.
위의 통계를 기반으로 일정 기간 이후의 예상 인구를 출력합니다.

>>>코드

for _ in range(int(input())):
    p, t = map(int, input().split())
    p = p + (t//4) - (t//7)
    print(p)
728x90
반응형
728x90
반응형

6/ 26 파이썬 공부
1. 백준 18698 The Walking Adam
Adam has just started learning how to walk (with some help from his brother Omar), and he falls down a lot. In order to balance himself, he raises his hands up in the air (that’s a true story), and once he puts his hands down, he falls.

You are given a string, each character represents a step he walks, if that character is ‘U’ that means his hands are up in this step, if this character is ‘D’ that means his hands are down and he fell down in this step. Your task is to count how many steps he will walk before falling down for the first time.

Your program will be tested on one or more test cases. The first line of the input will be a single integer T (1 ≤ T ≤ 100) representing the number of test cases. Followed by T test cases.

Each test case will consist of a single line, containing a non-empty string of at most 100 characters, and each character is either ‘U’ or ‘D’. The characters from left to right represent Adam’s steps in the order he walks them.

For each test case print a single line containing the number of steps that Adam will walk before falling down, or the length of the string if he won’t fall down.

>>>해석
이제 막 걸음마를 떼기 시작한 아담은, 자주 넘어지고 있습니다. 
아직 아담은 손을 번쩍 들어 올린 상태여야만 걸을 수 있고, 손을 내리게 되면 균형을 잃고 넘어지고 맙니다.
아담의 행동을 나타내는 'U' 와 'D'로만 구성된 문자열이 주어집니다. 
각각 'U'는 아담이 손을 들어 올린 상태임을, 'D'는 아담이 손을 내린 상태임을 의미합니다.
아담의 걸음마 연습을 도와주기 위해, 아담이 처음으로 넘어지기 전까지 몇 걸음을 걸었는지 계산해주는 프로그램을 작성해봅시다.

입력의 첫 줄에는 테스트 케이스의 개수를 뜻하는 정수 T (1 ≤ T ≤ 100)가 주어집니다.

각 테스트 케이스에는 아담의 행동을 시간순으로 나타낸 최대 100자 이내의 문자열 한 줄이 입력됩니다. 
해당 문자열은 공백이 존재하지 않고 'U'와 'D'로만 구성되어 있습니다.

각 테스트 케이스에 대해 아담이 처음으로 넘어질 때까지의 걸음 수를 출력합니다.

>>>코드

for _ in range(int(input())):
    s = input()
    result = 0
    for i in s:
        if i == 'D':
            break
        result += 1
    print(result)



2. 백준 21633 Bank Transfer
Tanya has an account in "Redgotts" bank. The bank has the commission to transfer money to "Bluegotts" bank that her friend Vanya has the account in.
Tanya has read her bank rules and learned the following:
The commission for the bank transfer is 25 tugriks plus 1% of the sum transferred. However, the commission is never smaller than 100 tugriks, and cannot exceed 2000 tugriks.
Tanya is planning to transfer k tugriks to Vanya. 
Help her find out what the commission would be.

Input is a single integer k (200 <= k <= 10^9).
Output one floating point value: the commission for the transfer. 
The value must be printed with at least two exact digits after the decimal point.

>>>해석
타냐는 레드고츠 은행에 계좌가 있습니다. 
그녀의 친구 바냐가 계좌를 가지고 있는 블루고츠 은행에 돈을 이체하려면 수수료를 내야 합니다.
타냐는 은행 약관을 보고 아래의 내용을 알게 됐습니다:
계좌 이체에 드는 수수료는 25 투그릭에 이체한 가격의 1%를 더한 값입니다. 
수수료는 최소 100 투그릭이며, 2000 투그릭을 넘지 않습니다.
타냐는 k 투그릭을 바냐에게 이체할 생각입니다. 그녀가 수수료가 얼마일지 계산하는 것을 도와줍시다.

입력은 한 개의 정수 k입니다. (200 <= k <= 10 ^ 9)
계좌 이체 수수료를 나타내는 하나의 부동 소수점 값을 출력합니다. 
출력한 값은 최소한 소수점 둘째 자리까지 정확히 일치해야 합니다.

>>>코드

k = float(input())
n = 25 + k*0.01
if n<100:
    print('100.00')
elif n>2000:
    print('2000.00')
else:
    print('%.2f' %(n))



3. 백준 21612 Boiling Water
At sea level, atmospheric pressure is 100 kPa and water begins to boil at 100◦C. As you go above sea level, atmospheric pressure decreases, and water boils at lower temperatures. As you go below sea level, atmospheric pressure increases, and water boils at higher temperatures. A formula relating atmospheric pressure to the temperature at which water begins to boil is

P = 5 × B − 400

where P is atmospheric pressure measured in kPa, and B is the temperature at which water begins to boil measured in ◦C.

Given the temperature at which water begins to boil, determine atmospheric pressure. Also determine if you are below sea level, at sea level, or above sea level.

Note that the science of this problem is generally correct but the values of 100◦C and 100 kPa are approximate and the formula is a simplification of the exact relationship between water’s boiling point and atmospheric pressure.

The input is one line containing an integer B where B ≥ 80 and B ≤ 200. This represents the temperature in ◦C at which water begins to boil.

The output is two lines. The first line must contain an integer which is atmospheric pressure measured in kPa. The second line must contain the integer -1, 0, or 1. This integer represents whether you are below sea level, at sea level, or above sea level, respectively.

>>>해석
해수면에서 기압은 100kPa이고 물은 섭씨 100도에서 끓기 시작합니다. 
해수면보다 높이 올라가면 기압이 내려가고, 물은 보다 낮은 온도에서 끓습니다. 
해수면 아래로 내려가면 기압은 올라가고, 물은 보다 높은 온도에서 끓습니다. 
기압과 물이 끓기 시작하는 온도의 관계를 서술하는 공식은 아래와 같습니다.

P = 5 * B - 400

P는 kPa 단위로 표현한 기압을, B는 섭씨 단위로 표현한 물이 끓기 시작하는 온도를 나타냅니다.
물이 끓기 시작하는 온도가 주어졌을 때, 기압을 구합시다. 
또한 현재 해수면 아래에 있는지, 해수면에 있는지, 혹은 해수면 위에 있는지도 판정합시다.
참고로 이 문제가 서술하는 과학은 대체적으로 맞지만, 섭씨 100도와 100kPa은 추정일 뿐이며 공식 역시 물이 끓기 시작하는 온도와 기압의 정확한 관계를 단순화한 것임을 알아둡시다.

한 줄에 B >= 80이고 B <= 200인 정수 B가 주어집니다. 
이것은 물이 끓기 시작하는 온도를 섭씨 단위로 표현한 값입니다.

출력은 두 줄입니다.
첫 줄은 kPa 단위로 표현한 기압을 나타내는 정수를 출력합니다. 둘째 줄은 -1, 0, 또는 1을 출력합니다. 
이는 각각 현재 해수면 아래에 있는지, 해수면에 있는지, 해수면 위에 있는지 나타내는 값입니다.

>>>코드

B = int(input())
P = 5 * B - 400
print(P)
if P > 100:
    print(-1)
elif P < 100:
    print(1)
else:
    print(0)
728x90
반응형
728x90
반응형

6/ 25 파이썬 공부
1. 백준 27332 
2 つの整数 A, B が与えられる.
2022 年 11 月 A 日の B 週間後の日が 2022 年 11 月ならば 1 を,2022 年 11 月でないならば 0 を出力せよ.
ただし,2022 年 11 月は 2022 年 11 月 1 日から 2022 年 11 月 30 日までの 30 日間であり,x 週間後の日とは (7 × x) 日後の日のことを指す.入力は以下の形式で与えられる.

A
B

2022 年 11 月 A 日の B 週間後の日が 2022 年 11 月ならば 1 を,2022 年 11 月でないならば 0 を出力せよ.

- 1 ≦ A ≦ 30.
- 1 ≦ B ≦ 5.
- 入力される値はすべて整数である

>>>해석
2개의 정수 A, B가 주어진다.
2022년 11월 A일의 B주일 후가 2022년 11월이면 1을, 아니면 0을 출력하라.
이때, 2022년 11월은 2022년 11월 1일부터 2022년 11월 30일까지 30일을 의미하며, 
x주일 후의 날짜는 7*x일 후를 의미한다. 입력은 다음과 같은 형태로 주어진다.

A
B

2022년 11월 A일의 B주일 후가 2022년 11월이면 1을, 2022년 11월이 아니면 0을 출력한다.

- 1 ≦ A ≦ 30.
- 1 ≦ B ≦ 5.
- 입력되는 모든 값은 정수이다.

>>>코드

a = int(input())
b = int(input())
if a + b*7 <= 30:
    print(1)
else:
    print(0)



2. 백준 6810 ISBN
The International Standard Book Number (ISBN) is a 13-digit code for identifying books. These numbers have a special property for detecting whether the number was written correctly.

The 1-3-sum of a 13-digit number is calculated by multiplying the digits alternately by 1’s and 3’s (see example) and then adding the results. For example, to compute the 1-3-sum of the number 9780921418948 we add

9 ∗ 1 + 7 ∗ 3 + 8 ∗ 1 + 0 ∗ 3 + 9 ∗ 1 + 2 ∗ 3 + 1 ∗ 1 + 4 ∗ 3 + 1 ∗ 1 + 8 ∗ 3 + 9 ∗ 1 + 4 ∗ 3 + 8 ∗ 1

to get 120.

The special property of an ISBN number is that its 1-3-sum is always a multiple of 10.

Write a program to compute the 1-3-sum of a 13-digit number. To reduce the amount of typing, you may assume that the first ten digits will always be 9780921418, like the example above. Your program should input the last three digits and then print its 1-3-sum. Use a format similar to the samples below.

>>>해석
국제 표준 도서 번호(ISBN)는 책을 식별하기 위한 13자리 번호입니다. 
이 번호에는 번호가 제대로 쓰인 것인지 확인할 수 있는 특별한 성질이 숨겨져 있습니다.

13자리 숫자의 1-3 합은 각 자리를 번갈아 1과 3으로 곱한 후 (예시를 참고합시다.) 그 값들을 더해 구할 수 있습니다. 예를 들어, 9780921418948의 1-3 합은 아래와 같은 덧셈을 통해 120임을 알 수 있습니다.

9 ∗ 1 + 7 ∗ 3 + 8 ∗ 1 + 0 ∗ 3 + 9 ∗ 1 + 2 ∗ 3 + 1 ∗ 1 + 4 ∗ 3 + 1 ∗ 1 + 8 ∗ 3 + 9 ∗ 1 + 4 ∗ 3 + 8 ∗ 1

ISBN의 특별한 성질은 1-3 합이 언제나 10의 배수라는 것입니다.

13자리 수의 1-3 합을 계산하는 프로그램을 작성합시다. 
타자 양을 줄이기 위해, 첫 열 개의 자리는 언제나 위의 예시와 같이 9780921418이라 가정합시다. 
당신의 프로그램은 마지막 세 자리를 입력 받아 1-3 합을 출력해야 합니다. 
아래의 예제와 같은 형식으로 출력합시다. (The 1-3-sum is 120)

>>>코드

a = int(input())
b = int(input())
c = int(input())
r = 91 + a*1 + b*3 + c*1
print('The 1-3-sum is %d' %(r))



3. 백준 18330 Petrol
The government of Neverland has recently announced a new petrol rationing plan with an unexpected price hike. According to the new plan, each person receives a quota of 60 liters per month in a fuel card. Each liter of petrol costs 1500 Oshloobs if it is within quota. Any extra fueling costs 3000 Oshloobs per liter.

After recovering from the shock, Mahya is trying to figure out how dark is the future. The current month is coming to an end, and Mahya has some quota left in her fuel card, remaining available for the next month. A quota of 60 liters will also be added to her fuel card just at the beginning of the next month. She also has a prediction of the amount of petrol that will be used in the next month. She now wants to know how much she should pay for petrol in the next month. However, she is too lazy to do that on her own. So, she needs your help to calculate the cost for her. 

The input consists of two lines. The first line contains an integer n (0 ⩽ n ⩽ 200), specifying the amount of petrol that will be used in the next month. The second line contains an integer k (0 ⩽ k ⩽ 360), showing the quota left in Mahya’s fuel card at the end of current month.
Print the amount of money (in Oshloobs) that Mahya will pay for petrol in the next month.

>>>해석
네버랜드 정부는 최근 예기치 못한 가격 급등에 따라 새로운 휘발유 배급 계획을 발표했습니다. 
새 계획에 따르면, 각 국민은 연료 카드에 월 60L를 한도로 설정 받습니다. 
한도 내에서 휘발유 1L는 1500 오쉬룹의 가치를 지닙니다. 
그 이상의 연료는 1L마다 3000 오쉬룹의 가치를 지닙니다.

가격 파동에서 회복된 뒤, 마히야는 미래가 얼마나 암울한지 전망하려 합니다. 
이번 달은 거의 끝나가고, 마히야는 연료 카드에 다음 달로 이월 가능한 남은 한도가 약간 있습니다. 
60L 한도는 다음 달이 시작할 때 추가로 더해질 것입니다. 그녀는 다음 달에 얼마만큼 휘발유를 쓸지도 예측했습니다. 그녀는 다음 달에 휘발유 값으로 얼마를 내야 하는지 알고 싶어합니다. 하지만 그녀는 게을러 직접 계산하지 못합니다. 따라서 당신이 그녀를 도와 휘발유 값을 계산해야 합니다. 

입력은 두 줄입니다. 첫 줄에는 다음 달 사용할 휘발유의 양을 나타내는 정수 n (0 <= n <= 200)이 주어집니다. 
둘째 줄에는 이번 달 마히야의 연료 카드에 남아있는 한도를 나타내는 정수 k가 주어집니다. 
마히야가 다음 달에 내야 하는 휘발유 값을 (오쉬룹 기준으로) 출력합니다.

>>>코드

a = int(input())
b = int(input())
if a <= 60 + b:
    print(1500 * a)
else:
    print(1500 * (60+b) + 3000 * (a-b-60))
728x90
반응형

+ Recent posts