About Me

我的相片
Taipei<->HsinChu, Taiwan
我是 Mashi,叫我 媽許、罵許,我都會回頭XD
2008年1月2日 星期三

[教學] Programming 6: "just another calculation"

題目網址

時間限制:1.5秒

題目大意:

給定一等式,算出結果。

Ex. The equation is "[x]29=-[1REa]47+[6D4e]41-[1A8903]14+[HDI1]21-[5SKX]53+[4W77]59+[7NS3]48+[5FSE]29-[1aUa]52"


解法:

基底轉換運算。

以下程式以 Ruby 執行
# Author      : mashimaro
# Last Modify : 2008/01/02

require 'net/http'
require 'net/https'

host = 'www.bright-shadows.net'
path = '/challenges/programming/calculate2/tryout.php'
cookie = 'PHPSESSID=************************************'

http = Net::HTTP.new(host, 80)
#http.use_ssl = true
headers = {
'Cookie' => cookie,
# 'Referer' => 'http://profil.wp.pl/login.html',
# 'Content-Type' => 'application/x-www-form-urlencoded'
}

resp, data = http.get(path, headers);

data.sub!('The equation is "', '');
data.sub!('"', '');
data.sub!('=[', '=+[');

puts data;

bases = [];
data.scan(/\][0-9]+/).each { |tmp_base|
bases.push(tmp_base[1..-1].to_i);
}
signs = ['+'];
data.scan(/[+-]\[/).each { |tmp_sign|
signs.push(tmp_sign[0..0]);
}
nums = [];
data.scan(/\[[0-9a-zA-Z]+\]/).each { |tmp_num|
nums.push(tmp_num[1..-2]);
}

#puts bases;
#puts signs;
#puts nums;

chrs = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

i = 1;
sum = 0;

while(i < bases.length)

num = 0;
nums[i].split(//).each { |c|
num = num * bases[i] + (chrs.index(c));
}

num = -num if(signs[i] == '-');

puts signs[i]+'['+nums[i]+']_'+bases[i].to_s+"\t"+num.to_s;

sum = sum + num;

i = i + 1;

end

tmp = sum;
(tmp = -tmp) if(tmp < 0);

result = '';

while(tmp > 0)
x = tmp % bases[0];
result = chrs[x..x] + result;
tmp = tmp / bases[0];
end

(result = '-' + result) if(sum < 0);

ret_path = '/challenges/programming/calculate2/solution.php?solution=' + result;

resp, data = http.get(ret_path, headers);

puts data;


消息來源

0 意見:

 
Blogger Template Layout Design by [ METAMUSE ] : Code Name BlackCat 2.0.0