[스터디] 문제 풀이 - 1주차

CHAEN·2022년 7월 7일
0

알고리즘 스터디

목록 보기
5/11

브 - 10101, 6502, 16478
실 - 2477, 3135, 16435
골 - 13904


10101번

문제

3개의 각을 입력 받아 합이 180인지 먼저 확인, 그 후 set 길이에 따라 삼각형 종류 판별

파이썬 풀이

angle = [int(input()) for _ in range(3)]

answer = ''

if sum(angle) == 180:
    angle = set(angle)
    if len(angle) == 1:
        answer = 'Equilateral'
    elif len(angle) == 2:
        answer = 'Isosceles'
    else:
        answer = 'Scalene'
        
else:
    answer = 'Error'

print(answer)

C++ 풀이

#include <iostream>
#include <set>
#include <vector>
#include <string> 
#include <numeric>

using namespace std;

int main(){
    vector<int> angle(3);
    string answer;
    
    for(int i = 0; i < 3; ++i){
        cin >> angle[i];
    }

    if(accumulate(angle.begin(), angle.end(), 0) == 180){
        set<int> temp(angle.begin(), angle.end());
        if(temp.size() == 1){
            answer = "Equilateral";
        }
        else if(temp.size() == 2){
            answer = "Isosceles";
        }
        else{
            answer = "Scalene";
        }
    }
    else{
        answer = "Error";
    }

    cout << answer;
    
    return 0;
}

* 벡터 등 컨테이너의 합을 구하는 방법
<numeric>헤더의 accumulate를 사용한다.
accumulate(시작, 끝, 초기값)
초기값에 따라 결과의 형식이 달라진다 (int, float, long long 등)

6502번

문제

피자의 대각선 길이가 테이블의 지름보다 작거나 같은지 확인, 0이 하나 들어오면 반복문이 멈출 수 있게!

파이썬 풀이

import math

p = 1

while True:
    answer = ''
    try:
        r, w, l = map(int, input().split())
    except:
        break
      
    d = math.sqrt(w**2 + l**2)
    
    if d > (r*2):
        answer = 'does not fit on the table.'
    else:
        answer = 'fits on the table.'
        
    print(f'Pizza {p} {answer}')
    
    p += 1

C++ 풀이

#include <iostream>
#include <cmath>

using namespace std;

int main(){
    int p = 1;
    int r, w, l;
    float d;

    while(1){
        cin >> r;
        if(r == 0) break;

        cin >> w >> l;

        d = sqrt(w*w + l*l);

        if(d > (r*2)){
            printf("Pizza %d does not fit on the table. \n", p);
        }
        else{
            printf("Pizza %d fits on the table. \n" , p);
        }
        ++p;        
    }

    return 0;
}

파이썬은 r, w, l 세 개를 모두 입력하지 않으면 오류가 발생해서 이를 예외처리로 프로그램을 종료할 수 있었는데 C++은 입력이 들어오지 않으면 그냥 기다리고 있었다..
에러가 안나;;
이걸 어떻게 처리할까 하다가 그냥 r값만 따로 받아주고 r이 0인지만 판별해주었다.

16478번

문제

Pa * Pb = Pc * Pd

파이썬 풀이

P_ab, P_bc, P_cd = map(int, input().split())

P_ad = P_ab * P_cd / P_bc

if P_ab == P_cd & P_cd == P_bc:
    P_ad = int(P_ad)

print(P_ad)

문제를 잘못이해해서 입력값 3개가 모두 같을 때는 반드시 정수형으로 출력해야 하는 줄 알앗당..

C++ 풀이

#include <iostream>
//#include <iomanip>

using namespace std;

int main(){
    int P_ab, P_bc, P_cd;

    scanf("%d %d %d", &P_ab, &P_bc, &P_cd);
    printf("%.7f", (double)P_ab * P_cd / P_bc);
}

부동소수점 정확도 지대 짱나;;


2477번

문제

큰 사각형에서 작은 사각형을 빼준다, 작은 사각형의 가로, 세로 길이는 큰 사각형의 세로, 가로 인덱스+3

파이썬 풀이

melon = int(input())
melon_map = []
max_width = 0
max_height = 0
max_width_idx = 0
max_height_idx = 0
del_area = 0

for i in range(6):
    d, l = map(int, input().split())
    # 가로
    if d == 2 or d == 1:
        if l > max_width:
            max_width = l
            max_width_idx = i
    # 세로
    elif d == 3 or d == 4:
        if l > max_height:
            max_height = l
            max_height_idx = i
            
    melon_map.append((d, l))

del_area = melon_map[(max_height_idx + 3) % 6][1] * melon_map[(max_width_idx + 3) % 6][1]
    
print((max_width * max_height - del_area)*melon)

C++ 풀이

#include <iostream>
#include <vector>

using namespace std;

int main(void){
    int melon;
    vector<pair<int, int>> melon_map;
    int max_width = 0;  int max_height = 0;
    int max_width_idx = 0;  int max_height_idx = 0;
    int del_area = 0;
    
    scanf("%d", &melon);

    for(int i = 0; i < 6; ++i){
        int d, l;
        scanf("%d %d", &d, &l);

        if(d == 1 || d == 2){ // 가로
            if(l > max_width){
                max_width = l;
                max_width_idx = i;
            }
        }
        else{ // 세로   
            if(l > max_height){
                max_height = l;
                max_height_idx = i;
            }
        }
        melon_map.push_back(make_pair(d, l));
    }
    
    del_area = melon_map[(max_height_idx + 3) % 6].second * melon_map[(max_width_idx + 3) % 6].second;
    printf("%d", (max_width * max_height - del_area) * melon);
}

3135번

문제

현재 주파수인 A에서 B로 이동하는게 더 빠른지, 저장된 주파수에서 B로 이동하는 것이 더 빠른지 비교

파이썬 풀이

a, b = map(int, input().split())
n = int(input())

freq = []

answer = abs(a-b)

for _ in range(n):
    f = int(input())
    freq.append(abs(b - f) + 1)

min_click = min(freq)
answer = min(answer, min_click)
print(freq)

C++ 풀이

#include <iostream>
#include <vector>

using namespace std;

int main(){
    int a, b, n;
    scanf("%d %d", &a, &b);
    scanf("%d", &n);
    vector<int> freq;

    int min = abs(a - b);
    
	# 저장된 주파수 입력받기
    for(int i = 0; i < n; ++i){
        int f;
        scanf("%d", &f);
        # 버튼 누르는 수를 계산해서 넣어준다
        freq.push_back(abs(f - b) + 1);
    }
    for(auto f : freq){
    	# 저장된 주파수를 누를 것인지 A에서 B로 이동할지 결정하기 위해 비교한다
        if(f < min){
            min = f;
        }
    }
    printf("%d", min);

    return 0;
}

16435번

문제

과일의 위치를 오름차순 정렬해준 뒤 먹을 수 있는 건 모두 먹는다

파이썬 풀이

n, l = map(int, input().split())
fruit = list(map(int, input().split()))
fruit.sort()

for h in fruit:
    if h > l:
        break
    else:
        l += 1
print(l)    

C++ 풀이

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    int n, l;
    # 과일의 개수와 처음 길이 입력
    scanf("%d %d", &n, &l);
    vector<int> fruit(n);
    
    # 과일의 위치 입력 받기
    for(int i = 0; i < n; ++i){
        cin >> fruit[i];
    }
    # 오름차순 정렬
    sort(fruit.begin(), fruit.end());
    
    # 먹을 수 있는 과일은 모두 먹기
    for(auto h:fruit){
        if(h > l) break;
        else l++;    
    }
    cout << l;

    return 0;
}

알고리즘 헤더 안넣어서 sort부분 에러났다.
왜 vscode에서는 돌아갔을까 흠..


13904번

문제

마감일까지 남은 과제 중 가장 점수가 큰 것을 골라서 할 수 있도록 점수를 내림차순 정렬

오답

n = int(input())

max_day = 0
score = []

for _ in range(n):
    d, w = map(int, input().split())
    if d > max_day:
        max_day = d
    score.append(w)
    if len(score) > max_day:
        score.sort(reverse=True)
        score = score[:max_day]

print(sum(score))

반례) 1 20 / 3 10 / 5 60 / 2 5 / 2 10

전체 입력받고 마감일 기준으로 정렬한 후 동일한 방법 적용!

파이썬 풀이

n = int(input())

max_day = 0
temp = []
score = []

for _ in range(n):
    d, w = map(int, input().split())
    temp.append((d, w))
    
temp = sorted(temp, key=lambda x: x[0])

for d, w in temp:
    if d > max_day:
        max_day = d
    score.append(w)
    if len(score) > max_day:
        score.sort(reverse=True)
        score = score[:max_day]

print(sum(score))

C++ 풀이

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
    // d 기준 오름차순 정렬
    return a.first < b.first;
}

int main(){
    vector<pair<int, int>> temp;
    vector<int> score;
    int n, answer;
    scanf("%d", &n);

    for(int i = 0; i < n; ++i){
        int d, w;
        scanf("%d %d", &d, &w);
        temp.push_back(make_pair(d, w));
    }
    sort(temp.begin(), temp.end(), cmp);

    int max_day = 0;
    for(auto p:temp){
        if(p.first > max_day)    max_day = p.first;
        score.push_back(p.second);
        if(score.size() > max_day){
        	// w 기준 내림차순 정렬
            sort(score.rbegin(), score.rend());
            score.pop_back();
        }
    }

    answer = accumulate(score.begin(), score.end(), 0);

    printf("%d", answer);
}
profile
공부중입니다

0개의 댓글