pwnable 筆記 Toddler's Bottle - coin1

這題考察算法 (分治法) 通過二分法查找便可以解出


題目比較坑的一點是要求在30秒內完成,如果去nc pwnable.kr 9007的話速度會非常慢,一般猜到第四十多次就超時了,爲解決這個問題,需要把腳本放在pwnable服務器上去執行

$ ssh [email protected] -p2222
password: guest
$ cd /tmp
$ vim a.py
$ python a.py

解題腳本:(好久沒編程了,寫個二分法手都生了...)

#!/usr/bin/python
__author__ = "TaQini"

from pwn import *
import re

def getNC():
	r = target.readline() #number and changes
	NC = re.findall("[0-9]+",r)
	return int(NC[0]), int(NC[1])

def guess(start, end):
    coin = ""
    for i in xrange(start, end+1):
        coin += str(i) + " "
    # print "coin " + coin
    target.sendline(coin)
    weight = target.read()
    # print "weight " + str(weight)
    return weight

def binsearch():
	for i in range(100):
		N, C = getNC()
		cnt = 0
		# print "N= " + str(N) + " C=" + str(C)
		Left = 0
		Right = N - 1
		while (Left <= Right):
			Mid = (Left + Right)/2
			# print "guess " + str(Left) + "-" + str(Mid)
			cnt += 1
			if cnt > C:
				# print "Hit!"
				weight = guess(Left,Mid)
				break
			else:
				weight = guess(Left,Mid)
				# print "trial= " + str(cnt)
				# print "and C= " + str(C)
				if (eval(weight) + 1) % 10:  # fake coin not here
					Left = Mid + 1
				else:
					Right = Mid
		print "hit!",(i),

target = remote("127.0.0.1",9007)
target.read() #rule of game
binsearch()
print target.read()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章