Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Week4] 전현수: 근손실, 톱니바퀴, 트리의 부모 찾기, 회의실 배정, 지름길 #18

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

soopeach
Copy link
Member

@soopeach soopeach commented Oct 23, 2022

Issue Number

Issue #17


💎 문제 해결


🔥 특이사항/질문

자유롭게 작성해주세요!

오호... 별건 아니지만... dp문제 거의 처음으로 혼자 풀어봐서 기쁘네요,,,

@soopeach soopeach self-assigned this Oct 23, 2022
Comment on lines +178 to +180
fun <T> Array<T>.second(): T = this[1]
fun <T> Array<T>.third(): T = this[2]
fun <T> Array<T>.fourth(): T = this[3]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@soopeach ???...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gongdongho12
보기 좋으라고 해봤는데...ㅎㅎ 안쓰느니만 못하나요??

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 왜 안지우는거에요? Iterator는 그냥 자동으로 destructure 지원되서 사용 안해도 되요!

@gongdongho12 gongdongho12 linked an issue Oct 23, 2022 that may be closed by this pull request
Comment on lines +88 to +91
val gear1 = gearList.first()
val gear2 = gearList.second()
val gear3 = gearList.third()
val gear4 = gearList.fourth()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@soopeach 이건 어떠세요?

val (gear1, gear2, gear3, gear4) = gearList

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 야무지네요...

@soopeach soopeach changed the title [Week4] 전현수: 근손실, 톱니바퀴, 트리의 부모 찾기, 회의실 배정 [Week4] 전현수: 근손실, 톱니바퀴, 트리의 부모 찾기, 회의실 배정, 지름길 Oct 23, 2022
*
*/

val exerciseKitList = mutableListOf<Int>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이런부분 lateinit 해주세요!!!!!!

possibleCaseCnt++
return
}
for (index in 0 until exerciseKitList.size) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이부분 exerciseKitList.forEachIndexed 했으면 어땠을까요?

Copy link
Member

@gongdongho12 gongdongho12 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4주차 하나 드디어 끝냈네요
늦어져서 죄송합니다 ㅠ

Comment on lines +29 to +40
val shortCutGraph = Array(10001) {
mutableListOf<ShortCutData>()
}

repeat(shortCutCnt) {
val (start, end, shortCutDistance) = readln().split(" ").map { it.toInt() }
// 도착지점이 고속도로의 길이를 넘거나 지름길이 도로보다 길지 않은 경우에만 지름길 생성
if ((end > highWayLength).not() &&
(end - start <= shortCutDistance).not()
) shortCutGraph[end].add(ShortCutData(start, shortCutDistance))

}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이부분 코틀린의 groupBy를 활용해보면 쓸데없는 데이터는 안 만들 수 있지 않을까요?

val shortCutGraph: Map<Int, List<ShortCutData>> = (0 until shortCutCnt).mapNotNull {
    val (start, end, shortCutDistance) = readln().split(" ").map { it.toInt() }
    if (end <= highWayLength && (end - start) > shortCutDistance) {
        end to ShortCutData(start, shortCutDistance)
    } else null
}.groupBy({ it.first }, { it.second })

Comment on lines +42 to +49
for (end in 1..highWayLength) {
dp[end] = dp[end - 1] + 1
if (shortCutGraph[end].isNotEmpty()) {
shortCutGraph[end].forEach { shortCutData ->
dp[end] = min(dp[end], dp[shortCutData.start] + shortCutData.distance)
}
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이부분도 minOf를 써서 잘 활용해서

(1..highWayLength).forEach { end ->
    dp[end] = dp[end - 1] + 1
    dp[end] = shortCutGraph[end]?.minOf {
        dp[it.start] + it.distance
    }?.takeIf { it < dp[end] } ?: dp[end]
}

minOf 한 값이 dp[end] 보다 작으면 진짜 최솟값인거고 아니면 null 리턴해서 dp[end]를 리턴하는거에요!

Comment on lines +28 to +36
class Gear(stateData: String) {

private val state = IntArray(8)

init {
stateData.forEachIndexed { index, charNum ->
state[index] = charNum.digitToInt()
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class Gear(val state: IntArray) {
        constructor(str: String): this(str.map { it.digitToInt() }.toIntArray())

Comment on lines +78 to +121
val gearList = Array(4) {
Gear(readln())
}

val affectedInfo = Array(4) {
mutableListOf<Int>()
}

fun solution() {

val gear1 = gearList.first()
val gear2 = gearList.second()
val gear3 = gearList.third()
val gear4 = gearList.fourth()

val rotateCnt = readln().toInt()

val rotateInfoList = Array(rotateCnt) {
val (gearNum, dir) = readln().split(" ").map { it.toInt() }
RotateInfo(gearNum, dir)
}

rotateInfoList.forEach { rotateInfo ->

val (gearNum, dir) = rotateInfo

val (firstLeft, firstRight) = gear1.getPole()
val (secondLeft, secondRight) = gear2.getPole()
val (thirdLeft, thirdRight) = gear3.getPole()
val (fourthLeft, fourthRight) = gear4.getPole()

// 회전에 영향을 받을 기어 판정
if (firstRight != secondLeft) {
affectedInfo[0].add(1)
affectedInfo[1].add(0)
}
if (secondRight != thirdLeft) {
affectedInfo[1].add(2)
affectedInfo[2].add(1)
}
if (thirdRight != fourthLeft) {
affectedInfo[2].add(3)
affectedInfo[3].add(2)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

val gearList = Array(4) {
    Gear(readln())
}.toList()

val affectedInfo = Array(4) {
    mutableListOf<Int>()
}

fun solution() {

    val rotateCnt = readln().toInt()

    val rotateInfoList = Array(rotateCnt) {
        val (gearNum, dir) = readln().split(" ").map { it.toInt() }
        RotateInfo(gearNum, dir)
    }

    rotateInfoList.forEach { rotateInfo ->

        val (gearNum, dir) = rotateInfo

        gearList.windowed(2, 1).forEachIndexed { index, gears ->
            val (prev, next) = gears.map { it.getPole() }
            if (prev.second != next.first) {
                affectedInfo[index].add(index + 1)
                affectedInfo[index + 1].add(index)
            }
        }

어... 이런거 있을거같은데? 찾아보면 있더라구요!
머리를 쓰지 않으면 고생합니다 ㅠ

저도 windowed 같은게 있는지 몰랐어요

Comment on lines +129 to +132
var score = 0
repeat(4) { cnt ->
score += gearList[cnt].getTopState() * twoToPowOfExponent(cnt)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이건 이제 안할때 된거같지만

val score = gearList.mapIndexed { index, gear ->
    gear.getTopState() * twoToPowOfExponent(index)
}.sum()

택 1

val score = (0 until 4).sumOf { gearList[it].getTopState() * twoToPowOfExponent(it) }


val rootQueue: Queue<Int> = ArrayDeque()
val nodeCnt = readln().toInt()
val treeArray = Array(nodeCnt + 1) { mutableListOf<Int>() }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

중첩되지 않고 사실 순서보다는 실제 Collection의 값을 삭제하는 데에 초점을 맞췄게 때문에
mutableList 보다는 mutableSet 사용하시는게 이 로직에서는 훨씬 효율적이에요!

treeArray[curParent].forEach { child ->
parentNodeData[child] = curParent
// 방문 판정 -> 자식 노드에서 부모 노드 제거
treeArray[child].remove(curParent)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MutableSet이면 더 효율적으로 삭제될 수 있는 이유

Comment on lines +21 to +31
val meetingList = mutableListOf<MeetingData>()
var canMeetingCnt = 0
var endTime = 0

repeat(meetingCnt) {
val (start, end) = readln().split(" ").map { it.toInt() }
meetingList.add(MeetingData(start, end))
}

// 정렬
meetingList.sortWith(compareBy<MeetingData> { it.end }.thenBy { it.start })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

소팅을 통해 추가해야 하는 경우에는 PriorityQueue를 이용해봐요
이럴때 쓰라고 만들어진 친구입니다!

val pq = PriorityQueue(compareBy<MeetingData> { it.end }.thenBy { it.start })

Comment on lines +34 to +42
endTime = meetingList.first().end
canMeetingCnt++

meetingList.drop(1).forEach { meetingData ->
if (endTime <= meetingData.start) {
endTime = meetingData.end
canMeetingCnt++
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pq를 사용하면 drop 처리 안하고 그냥 뽑아주면 되겠죠?

endTime = pq.poll().end
canMeetingCnt++

while (pq.isNotEmpty()) {
    val meetingData = pq.poll()
    if (endTime <= meetingData.start) {
        endTime = meetingData.end
        canMeetingCnt++
    }
}

val meetingCnt = readln().toInt()
val meetingList = mutableListOf<MeetingData>()
var canMeetingCnt = 0
var endTime = 0
Copy link
Member

@gongdongho12 gongdongho12 Nov 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

항상 전역변수를 선언해줘야한다는 부분을 사용하는 부분에만 적용한다 생각해보시면 아래 endTime을 사용하는 부분에서 var 선언해주면 되지 않았을까 싶어요!

@gongdongho12 gongdongho12 added the review complete 리뷰 완료 label Nov 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
review complete 리뷰 완료
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[4주차 문제]
2 participants