P1 移动的圆
- 不要忘记考虑 ∣ R a − R b ∣ < = d |R_a-R_b| <= d ∣Ra−Rb∣<=d。
- 解法有三种:
2.1 一般情况下, lintcode测试集很弱,可以暴力的网格搜。
2.2 数学解, 求切点。判断是否在线段上
2.3 三分法求极值。
是不是觉得我很厉害,想了这么多方法。恩,比赛的时候我确实想到了,但是忘记了第一点,于是wa了半天, 最后也没过。 第一题,绝对是最难的。
class Solution:
"""
@param position: the position of circle A,B and point P.
@return: if two circle intersect return 1, otherwise -1.
"""
def IfIntersect(self, position):
xa, ya, ra, xb, yb, rb, xp, yp = position
sqmax = pow(ra+rb, 2)
sqmin = pow(ra-rb, 2)
print(sqmax, sqmin)
eps = 1e-9
def dist(x0,y0):
sq = pow(x0-xb, 2) + pow(y0-yb, 2)
return sq
step = 100000
for i in range(0, step+1):
x = (xp - xa) * i / step + xa
y = (yp - ya) * i / step + ya
if sqmin <= dist(x,y) <= sqmax:
return 1
return -1
P2 写作业
- 不说了秒过。
import bisect
class Solution:
"""
@param cost: the cost
@param val: the value
@return: the all cost
"""
def doingHomework(self, cost, val):
# Write your code here.
A = []
cur = 0
lim = 10 ** 5
for x in cost:
cur += x
if cur > lim: break
A.append(cur)
ret = 0
for x in val:
idx = bisect.bisect_right(A, x)
if idx > 0:
ret += A[idx-1]
return ret
P3 def串
- 居然标了个hard题, 有点惊呆。 经过4连wa后, 不愧是hard。
- 几个坑:
2.1 n太大了, 当n大于 l o g 2 ( 1 0 18 ) log_2(10^{18}) log2(1018)的时候, 我们总是去前半段。 可以加判断来提高效率。
2.2 2的幂需要预处理, 存一下。 一直重复算,就超时了。
2.3 python函数不带尾递归自动优化(应该是有的,我还没学会= =)。 写个递归函数,就爆栈。 - 一步一坑。 最后我还写错了一个变量, 又wa了。
class Solution:
"""
@param n: the length of the string.
@param k: the kth Lexicographically smallest that result should be.
@return: return the kth Lexicographically smallest string.
"""
def kthString(self, n, k):
# write your code here.
P = [1]*61
for i in range(1, 61):
P[i] = P[i-1] << 1
if n <= 60 and k > 3 * P[n-1]: return ""
R = []
pre = ""
if n >= 61:
R.append("d")
pre = "d"
elif k <= P[n-1]:
R.append("d")
pre = "d"
elif k <= P[n]:
R.append("e")
k -= P[n-1]
pre = "e"
else:
R.append("f")
k -= P[n]
pre = "f"
n-=1
while n>0:
if n>=61 or k <= P[n-1]:
if pre == "d":
R.append("e")
pre = "e"
else:
R.append("d")
pre = "d"
else:
if pre == "f":
R.append("e")
k -= P[n-1]
pre = "e"
else:
R.append("f")
k -= P[n-1]
pre = "f"
n-=1
return "".join(R)
P4 格式化字符串
- 打卡题, 为什么一直要放最后面。
class Solution:
"""
@param str: the original string
@param sublen: an integer array
@return: the new string
"""
def reformatString(self, str, sublen):
#
start = 0
A= []
for x in sublen:
A.append(str[start: start + x])
start += x
n = len(A)
k = n // 2
ret = ""
for i in range(n//2):
ret = ret + A[2*i+1] + A[2*i]
if n % 2 == 1:
ret += A[-1]
return ret