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 5 years have passed since last update.

paiza POH kirishima #paizahack_lite (Swift)

Last updated at Posted at 2015-12-08
問題 https://paiza.jp/poh/kirishima
C/Go/C#/VB/JavaScript http://qiita.com/cielavenir/items/aad18ccc8463e77a1c87
Java/CoffeeScript/Ruby/PHP/Python http://qiita.com/cielavenir/items/d07e62d1dc61c2915003
Perl/Scala/F#/D http://qiita.com/cielavenir/items/0b338f5c1b2e57ed915e
最速解答 http://qiita.com/cielavenir/items/2afc31eb9718e3170755
Swift http://qiita.com/cielavenir/items/16440e1e3713a41a3830

とりあえず、0.05s/0.22sという記録を出すことができた。
https://paiza.jp/poh/kirishima/result/1a27ff7a
以下がコードである。

paizapoh3.swift
//usr/bin/env xcrun swift $0 $@;exit

//let M=getInt(),N=getInt()
let M=Int(readLine()!)!,N=Int(readLine()!)!
var num=[Int](count:N,repeatedValue:0)
var cost=[Int](count:N,repeatedValue:0)
var total=0
var i=0,j=0

for j=0;j<N;++j {
	let a=readLine()!.characters.split{$0==" "}
	//let q=getInt()
	//let r=getInt()
	let q=Int(String(a[0]))!
	let r=Int(String(a[1]))!
	total+=q
	num[j]=q
	cost[j]=r
}
var bag=[Int](count:total+1,repeatedValue:0)
for i=1;i<=total;++i {bag[i] = -1}
var t=0
for j=0;j<N;++j {
	t+=num[j]
	for i=t;i>=num[j];--i {
		if bag[i-num[j]]>=0 {
			let x=bag[i-num[j]]+cost[j]
			if bag[i]<0||bag[i]>x {
				bag[i]=x
			}
		}
	}
}
j = -1
for i=M;i<=total;++i { if j<0||(bag[i]>=0&&j>bag[i]) {j=bag[i]}}
print(j)

しかし。let x=bag[i-num[j]]+cost[j]を変数にキャッシュせず展開するとTLEになる。
https://paiza.jp/poh/kirishima/result/2523d778
0.05秒 vs 3.00秒以上、である。60倍以上もの差。もはやSwiftの構文木のバグであるとしか思えない。とても怖い。

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?