0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【競プロ/Swift】まよコン 2023/03/28

Posted at

注意事項

本記事は復習のための日記的なものであり、丁寧な解説を求めている方には不十分かと思われますので、ご了承のほどお願いいたします。

正解済み問題

A - Repression

問題文
こちら問題ページ

解答
ソートして後ろ二つを足し算。

let abc = readLine()!.split(separator: " ").map{Int($0)!}.sorted()
print(abc[1] + abc[2])

B - Alcoholic

問題文
こちら問題ページ

解答
浮動小数点による誤差でだいぶ時間使った。
基本的に整数にしてから、計算するようにした方が良い。

let nx = readLine()!.split(separator: " ")
let n: Int = Int(nx[0])!
var x: Int = Int(nx[1])! * 100

var totalMl: Int = 0
var counter = 0
for _ in 1...n {
    let vp = readLine()!.split(separator: " ").map{Int($0)!}
    let ml = vp[0] * vp[1]
    
    totalMl += ml
    counter += 1
    if x < totalMl {
        break
    }
}

if x < totalMl {
    print(counter)
} else {
    print(-1)
}

誤答及び、未解答問題

D - Replacing

問題文
こちら問題ページ

誤答
馬鹿正直にループ気にせず解いてみたが、案の定TLEで終了。
他の方法も考えてみたが、結局分からなかった。

let n = Int(readLine()!)!
var aArray = readLine()!.split(separator: " ").map{Int($0)!}
let q = Int(readLine()!)!

for _ in 0..<q {
    let bc = readLine()!.split(separator: " ").map{Int($0)!}
    aArray.replace(before: bc[0], after: bc[1])
    print(aArray.reduce(0, +))
}


extension Array where Element: Equatable {
    mutating func replace(before: Array.Element, after: Array.Element) {
        self = self.map { ($0 == before) ? after : $0 }
    }
}

正答

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map{ Int(String($0))! }
}

let n = Int(readLine()!)!
let a = readInts()
let q = Int(readLine()!)!

let m = 100000
var s = a.reduce(0, +)
var counter = [Int](repeating: 0, count: m + 1)
a.forEach{ counter[$0] += 1 }

for _ in 0..<q {
    let query = readInts()
    let b = query[0], c = query[1]

    let diff = (c - b) * counter[b]
    counter[c] += counter[b]
    counter[b] = 0

    s += diff
    print(s)
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?