220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • Minimum Spanning Tree
  • Prefix Sum
  • Greedy
  • binary search
  • simulation
  • topological sort
  • Priority Queue
  • Backtracking
  • bitmasking
  • brute-Force
  • 티스토리챌린지
  • REACT
  • 위상 정렬
  • Mathematics
  • 프로그래머스
  • BFS
  • IMPLEMENT
  • two pointer
  • top-down
  • implementation
  • dfs
  • 오블완
  • 구현
  • Dynamic Programming
  • union-find
  • 다익스트라
  • disjoint set
  • Lis
  • dp

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 21608. 상어 초등학교 - Python

2023. 8. 25. 20:37

[Gold V]

 

https://www.acmicpc.net/problem/21608

 

21608번: 상어 초등학교

상어 초등학교에는 교실이 하나 있고, 교실은 N×N 크기의 격자로 나타낼 수 있다. 학교에 다니는 학생의 수는 N2명이다. 오늘은 모든 학생의 자리를 정하는 날이다. 학생은 1번부터 N2번까지 번호

www.acmicpc.net

 

풀이

3 <= N <= 20 이므로, 학생의 최대 수 및 최대 칸 수는 400.

400명의 학생 모두에게, 400칸에 대한 경우의 수를 계산하여도, 160,000개 정도밖에 나오지 않기 때문에,

시간 복잡도를 고려할 필요 없이, 단순 구현 문제라는 것을 알 수 있다.

 

자세한 설명은 주석으로 대체.

AC.

N = int(input())

fav = dict()
for _ in range(N**2):
    a = list(map(int, input().split()))
    fav[a[0]] = a[1:]

seat = [[0]*N for _ in range(N)]

dr = [1, 0, -1, 0]
dc = [0, 1, 0, -1]


def selectSeat(student):
    # 1번 조건은 우선도에 10 추가, 2번 조건은 우선도에 1 추가
    priority = [[0]*N for _ in range(N)]

    for r in range(N):
        for c in range(N):
            for k in range(4):
                nr = r + dr[k]
                nc = c + dc[k]

                # 범위를 벗어나지 않았는지
                if 0 <= nr < N and 0 <= nc < N:
                    # 좋아하는 학생이 있는 칸일 시 우선도 +10
                    if seat[nr][nc] in fav[student]:
                        priority[r][c] += 10
                    # 빈 칸일 시 우선도 +1
                    if seat[nr][nc] == 0:
                        priority[r][c] += 1

    # 우선도가 가장 높은 seat의 row, col을 return. 이미 우선도가 높은 좌석에 학생이 앉아 있다면 pass.
    # 우선도가 같은 것이 나왔다면, topList에 저장.
    # 이후 topList를 row, col 오름차순 정렬 후 첫 번째 것을 return.
    nowP = -100
    topList = []
    for r in range(N):
        for c in range(N):
            if priority[r][c] > nowP and seat[r][c] == 0:
                nowP = priority[r][c]
                topList = [(r, c)]
            elif priority[r][c] > nowP and seat[r][c] == 0:
                topList.append((r, c))

    topList = list(sorted(topList, key=lambda x: (x[0], x[1]), reverse=True))
    return topList[0]


# 학생들 앉히기
for student in fav.keys():
    i, j = selectSeat(student)
    seat[i][j] = student


def calculateSatisfaction(r, c):
    favStuCnt = 0
    for k in range(4):
        nr = r + dr[k]
        nc = c + dc[k]

        # 범위를 벗어나지 않았는지
        if 0 <= nr < N and 0 <= nc < N:
            # 좋아하는 학생이 있는 칸일 때 count++
            if seat[nr][nc] in fav[seat[r][c]]:
                favStuCnt += 1

    if favStuCnt == 0:
        return 0
    else:
        return 10**(favStuCnt-1)


satisfactionResult = 0
for i in range(N):
    for j in range(N):
        satisfactionResult += calculateSatisfaction(i, j)

print(satisfactionResult)

 

    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 12904. A와 B - Python
    • [백준] 14254. 비밀번호 변경 - Python
    • [백준] 16236. 아기 상어 - Python
    • [백준] 3109. 빵집 - C++
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바