Facebook Hacker Cup 2014 Qualification Round
2014 Qualification Round Solutions
。。。最简单的一题又有bug。。。自以为是真是很厉害!
1. Square Detector (20 Points)
When facing a problem in a programming contest there are three main things to consider when planning your solution. In order of importance:
- Is the algorithm correct.
- Is the algorithm fast enough.
- Is the algorithm easy to implement.
In this particular problem the first two points are rather straightforward, the task is conceptually simple and with the small input size efficiency is not a big concern.
The third point however deserves some consideration, I'm sure you are well aware that it's easy to make bugs in any piece of code you write, and chances for having bugs increase sharply with the code lengths and complexity. That's why it's worth to spend couple extra minutes to think about an approach that yields the least complicated code.
One clever way of solving this is to realize that if you take the bounding box of all the black cells all you need to check is that it's a square and that all the cells inside it are black. Since we are talking about the bounding box another way of stating the second condition is that: total number of black cells is equal to the area of our box.
With that observation the whole algorithm can be expressed with just these simple steps:
- Find the minimum and maximum X coordinate of all the black cells. The same for Y values
- Count all the black cells
- Check if maxX - minX == maxY - minY
- Check if the area: (maxX - mniX +1)^2 is equal to the count from step 2
- Profit!
A solution like that leaves much less room for an error than solutions with higher number of conditions to check, like for example finding segments in each row and then figuring out if they add up to a square. Here is an example python implementation:
def solve():
n = int(raw_input().strip())
b = [raw_input().strip() for i in range(n)]
black = 0
minX, maxX, minY, maxY = n, 0, n, 0
for x in range(0, n) :
for y in range(0, n) :
if b[x][y] == '#':
minX, minY = min(minX, x), min(minY, y)
maxX, maxY = max(maxX, x), max(maxY, y)
black += 1
dx = maxX - minX + 1
dy = maxY - minY + 1
return dx == dy and dx * dy == black
if __name__ == '__main__':
t = int(raw_input().strip())
for i in range(1, t+1):
res = solve()
print 'Case #%d: %s' % (i, 'YES' if res else 'NO')
Another idea of a very inefficient, but easy to implement algorithm is that you can iterate over all the possible grid formations that form a square, there is an order of N^3 of them. Now all you need to check is whether one of the grids matches your input exactly!
Finally with 20 cases and 5 minutes to upload the output, you can actually detect the squares by reading the input file with your own pair eyes :)
2. Basketball Game (35 Points)
Similarly to the previous problem the solution doesn't require fancy algorithm, and the execution speed is not a problem. You can basically solve it by translating the statement step by step into code to simulate what happens during the game.
The main difficulty in doing that is figuring out how to store and manipulate the state for each of the players. There are multiple pieces of information associated with a player: her name, height, shot accuracy, draft number, minutes played, and whether she's currently on the bench. With all that it might be useful to encapsulate it in a structure. I chose to have a Player class that stores all the aforementioned data. With that out of the way the solution can be done in three steps:
Step 1: Calculate draft numbers and split into teams
The easiest way to achieve this is to sort all the players by the defined criteria and then the 1-base index of a player in the sorted array is equal to the draft number of that player. Sorting things by various criteria is an often encountered operation in programming competitions so it's worth knowing how to do it in your language of choice. For example in python you can do it by passing a lambda function for key calculation, like this:
players.sort(key = lambda p: (p.perc, p.height), reverse=True)
for idx, player in enumerate(players):
player.draft = idx + 1
player.onField = idx < 2 * P
teamA = filter(lambda t: t.draft % 2 == 1, players)
teamB = filter(lambda t: t.draft % 2 == 0, players)
Step 2: Simulate a minute of the game and the rotation
Again we want to perform exactly what the problem statement asks us to. That is find the player with the most play time currently on the field and the player with the least play time from the bench. We can again use a lambda function together with min/max functions to achieve that.
def field(team): return filter(lambda p: p.onField, team)
def bench(team): return filter(lambda p: not p.onField, team)
def play(team):
for player in field(team): player.timePlayed += 1
def rotate(team):
max(field(team), key = lambda p: (p.timePlayed, p.draft)).onField = False
min(bench(team), key = lambda p: (p.timePlayed, p.draft)).onField = True
There is one subtlety in the rotate function above. It adds the player to the bench before selecting the player to join the field so it looks like it could allow for a player to leave and immediately come back. In practice this can never happen (for teams with more than P players) but if you are not convinced and don't feel like proving it just use a temporary variable rather than changing the state right away.
Step 3: Get the state after M minutes and print the result
After repeating the previous step M times there is one final thing to do. Find the players on the field and print out sorted list of names:
res = map(lambda p: p.name, field(teamA) + field(teamB))
print(" ".join(sorted(res)))
A final Note on the language selection, I've chosen Python for the examples because I enjoy the brevity and clarity it can offer. The problem can of course be solved in a more imperative way just fine. In the future rounds we might face more computationally heavy problems where benefits of a faster language like C++ can outweigh the elegance of Python.
3. Tennison (45 Points)
Let F(w, l, p) be the probability that Tennison the match given that he has already won w games, lost l games, and the probability of sun is currently p. Our answer will then be F(0, 0, pi).
First, the base cases. If you've already won K or lost K games, the match is over:
F(K, l, p) = 1.0
F(w, K, p) = 0.0
For each match, it can be sunny or rainy, Tennison can win or lose, and the weather can change or stay the same. That gives us 23 = 8 possible outcomes. Our answer will be the sum across all of these outcomes. The probability of each outcome is just the product of the probability of the 3 individual events.
F(w, l, p) =
p * ps * pw * F(w + 1, l, p + pu) +
p * ps * (1 - pw) * F(w + 1, l, p ) +
p * (1 - ps) * pl * F(w, l + 1, p - pd) +
p * (1 - ps) * (1 - pl) * F(w, l + 1, p ) +
(1 - p) * pr * pw * F(w + 1, l, p + pu) +
(1 - p) * pr * (1 - pw) * F(w + 1, l, p ) +
(1 - p) * (1 - pr) * pl * F(w, l + 1, p - pd) +
(1 - p) * (1 - pr) * (1 - pl) * F(w, l + 1, p )
If p is ever greater than 1, or less than 0, it's important to remember to cap it to the range [0, 1].
We need to memoize our results to have this solution run in time, but that might appear awkward since one of the inputs to F, p is a fraction. However, the probabilities are only given to 3 decimal places so it suffices to represent p as an integer in the range [0, 1000].
w and l can each be as large as K, and p can be as large as 1000, so the worst-case running time is proportional to 1000 * K2, which is 107.
Facebook Hacker Cup 2014 Qualification Round的更多相关文章
- Facebook Hacker Cup 2014 Qualification Round 竞赛试题 Square Detector 解题报告
Facebook Hacker Cup 2014 Qualification Round比赛Square Detector题的解题报告.单击这里打开题目链接(国内访问需要那个,你懂的). 原题如下: ...
- DP VK Cup 2012 Qualification Round D. Palindrome pairs
题目地址:http://blog.csdn.net/shiyuankongbu/article/details/10004443 /* 题意:在i前面找回文子串,在i后面找回文子串相互配对,问有几对 ...
- 51Nod 1182 完美字符串(字符串处理 贪心 Facebook Hacker Cup选拔)
1182 完美字符串 题目来源: Facebook Hacker Cup选拔 基准时间限制:1 秒 空间限制:1 ...
- Facebook Hacker Cup 2015 Round 1--Corporate Gifting(树动态规划)
原标题:https://www.facebook.com/hackercup/problems.php?pid=759650454070547&round=344496159068801 题意 ...
- Facebook Hacker Cup 2015 Round 1--Winning at Sports(动态规划)
原题:pid=688426044611322&round=344496159068801">https://www.facebook.com/hackercup/problem ...
- Facebook Hacker Cup 2015 Round 1--Homework(筛选法求素数)
题意:给定A,B,K(A<=B)三个数,问在[A,B]范围内的数素数因子个数为K的个数. 题解:典型的筛选法求素数.首先建立一个保存素数因子个数的数组factorNum[],以及到n为止含有素数 ...
- VK Cup 2012 Qualification Round 1 C. Cd and pwd commands 模拟
C. Cd and pwd commands Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/problemset ...
- VK Cup 2012 Qualification Round 2 C. String Manipulation 1.0 字符串模拟
C. String Manipulation 1.0 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 codeforces.com/problemset/pr ...
- VK Cup 2012 Qualification Round 1---C. Cd and pwd commands
Cd and pwd commands time limit per test 3 seconds memory limit per test 256 megabytes input standard ...
随机推荐
- IIS绑定Active Directory账号自动登录网站的方法
满足使用Request.ServerVariables["REMOTE_USER"]的条件: 1.IIS配置网站的目录安全性取消“启用匿名访问(&A)” 2.启用 “集成 ...
- 超简单的处理JSON格式和JSON数组格式的String
现在网站上有不少处理JSON格式的工具类,但是我找了一天,发现大都是需要编写相应对象类来进行处理,比较麻烦,比如:Gson,json-lib.Gson,json-lib这些处理那些接口之类的参数名字和 ...
- Python基本数据类型之int 、 float
首先要明确的是:在python中,一切皆为对象. 从底层角度看,对象就是保存在内存中的一个数据块.从抽象层看,对象就是我们的代码模拟出的一个类的独立个体. 在python中变量不需要声明类型,也不需要 ...
- 《Haskell趣学指南 Learn You a Haskell for Great Good!》-代码实验
doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumber x = then x else x * doub ...
- [LeetCode] Maximal Rectangle(good)
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and ...
- 面向对象世界里转转七(Liskov替换原则)
前言:Liskov替换原则是关于继承机制的应用原则,是实现开放封闭原则的具体规范,违反了Liskov原则必然意味着违反了开放封闭原则.因此,有必要对面向对象的继承机制及其基本原则做以探索,来进一步了解 ...
- asp:gridview 中显示日期格式
boundfield中应该这样设置: <asp:BoundField HeaderText="发表时间" DataField="PostTime" Htm ...
- Java学习-025-类名或方法名应用之一 -- 调试源码
上文讲述了如何获取类名和方法名,敬请参阅: Java学习-024-获取当前类名或方法名二三文 . 通常在应用开发中,调试或查看是哪个文件中的方法调用了当前文件的此方法,因而在实际的应用中需要获取相应的 ...
- imx6 启动 init进程
之前不知道imx6内核是怎么启动文件系统的init进程,查了下资料,记录于此,以后再来补充. kernel/init/main.c static noinline int init_post(void ...
- 树莓派连接wifi
使用树莓派,通过无线网卡连接wifi,再通过远程桌面或者ssh的连接树莓派比较方便,本文记录树莓派wifi如何设置. 参考链接: http://www.jianshu.com/p/b42e8d3df4 ...