Created
October 20, 2011 04:07
-
-
Save cb372/1300391 to your computer and use it in GitHub Desktop.
CodeJam 問題C. ビット数 first attempt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Ridiculous bit counting algorithm | |
* http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel | |
*/ | |
def f(x:Int):Int = { | |
var v = x - ((x >> 1) & 0x55555555) | |
v = (v & 0x33333333) + ((v >> 2) & 0x33333333) | |
(((v + (v >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24 | |
} | |
def findMax(N: Int) = { | |
var max = 0 | |
// Filter out the low-hanging fruit: case where both a and b are even | |
for (i <- (N/4 to N/2 filter(i => !(i%2 ==0 && (N-i)%2 == 0)))) { | |
max = math.max(max, f(i)+f(N-i)) | |
} | |
max | |
} | |
import scala.io.Source | |
val lines = Source.fromFile("C-small-practice.in").getLines() | |
lines.toList.tail.zipWithIndex.foreach{ valAndIndex => println("Case #"+(valAndIndex._2+1)+": "+findMax(valAndIndex._1.toInt)) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
日本語コメントできるのかな?
f()がなにやってるのかよくわからん…じっくり読んでみるよ。
Scalaのソースコードって初めて見るけど、読みやすいね。