백준_2167_DP(2회독)

hankyulee·2021년 12월 27일
0

Swift coding test 준비

목록 보기
49/57

답지 다시보기!

1회: 152ms

let given = readLine()!.split(separator: " ").map{Int($0)!}
let n = given[0]
let m = given[1]
var array : [[Int]] = [[Int]]()
for i in 0..<n{
    let row = readLine()!.split(separator: " ").map{Int($0)!}
    array.append(row)
}
//print(array)
var dp : [[Int]] = Array(repeating: Array(repeating: 0, count: m), count: n)
for i in 0..<n{
    for j in 0..<m{
        if i == 0 && j == 0{//0행 0열
            dp[i][j] = array[0][0]
        }
        else if i == 0 { // 0행
            dp[i][j] = dp[i][j-1] + array[i][j]
        }
        else if j == 0 {
            dp[i][j] = dp[i-1][j] + array[i][j]
        }
        else {
            dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + array[i][j]
        }
    }
}


let k = Int(readLine()!)!
var problem : [[Int]] = [[Int]]()
var answer = [Int]()
for i in 0..<k{
    let row = readLine()!.split(separator: " ").map{Int($0)!-1}

    let x1 = row[0]
    let y1 = row[1]
    let x2 = row[2]
    let y2 = row[3]
    
    let total = dp[x2][y2]
    let leftSide = x1 - 1 >= 0 ? dp[x1 - 1][y2] : 0
    let topSide = y1 - 1 >= 0 ? dp[x2][y1 - 1] : 0
    let commonSide = (x1 - 1 >= 0 && y1 - 1 >= 0) ? dp[x1-1][y1-1] : 0
    let result = total - leftSide - topSide + commonSide
    answer.append(result)
}
answer.forEach{
    print($0)
}

2회: 80ms

let rowAndCol = readLine()!.split(separator: " ").map{Int(String($0))!}
let row = rowAndCol[0]
let col = rowAndCol[1]
var mapp:[[Int]] = Array(repeating: Array(repeating: 0, count: col), count: row)
for r in 0..<row {
    let given = readLine()!.split(separator: " ").map{Int(String($0))!}
    for c in 0..<col{
        mapp[r][c] = given[c]
    }
}
var problems:[[Int]] = []
let numberOfCount = Int(readLine()!)!
for k in 0..<numberOfCount {
    let given = readLine()!.split(separator: " ").map{Int(String($0))!-1}
    problems.append(given)
}
var sumArray:[[Int]] = Array(repeating: Array(repeating: 0, count: col), count: row)

for r in 0..<row {
    var sum = 0
    for c in 0..<col{
        sum += mapp[r][c]
        sumArray[r][c] = sum
    }
}
for i in problems {
    var sum = 0
    let originRow = i[0]
    let originCol = i[1]
    let destinationRow = i[2]
    let destinationCOl = i[3]
    
    for r in originRow...destinationRow {
        sum += (sumArray[r][destinationCOl] - sumArray[r][originCol] + mapp[r][originCol])
    }
    print(sum)
}

0개의 댓글