homework-02 "最大子数组之和"的问题进阶
代码编写
这次的作业瞬间难了好多,无论是问题本身的难度或者是单元测试这一原来没接触过的概念或者是命令行参数的处理这些琐碎的问题,都使得这次作业的完成说不上轻松。
最大子数组之和垂直水平相连的拓展问题解决关键在于循环语句的适度改写,连通问题则是用递归搜索的方法来解决(效率没有实测),在15*15的情况下还是能较快得出结果的。
非常庆幸使用的是Python,Pyhton中很多语法能够保证我在编写代码时不用分太多的时间去处理数据输入,在处理问题上一些数组相关灵活的语法也很大程度上方便了代码的编写。
# coding:utf-8
'''
2013-9-30 XTH
'''
import sys def setglobalvar():
global max_sum,now_sum,min_x,min_y,num,visited,pointgroup
max_sum = 0
now_sum = 0
min_x = 0
min_y = 0
num = []
visited = {}
pointgroup = [] def maxsum_h(num,n1,n2):#水平上相连
line = [0]*n2
max_sum = 0 #最大和
now_sum = 0 #当前和
for l in range (0,n2):
for i in range(0,n1):
for j in range(i,n1):
for k in range(0+l,n2+l):
k = k % n2
line[k] += num[j][k]
if now_sum <0:
now_sum = 0
now_sum += line[k]
if now_sum > max_sum:
max_sum = now_sum
now_sum = 0
now_sum=0
line = [0]*n2
return max_sum def maxsum_v(num,n1,n2): #垂直上相连
line = [0]*n2
max_sum = 0 #最大和
now_sum = 0 #当前和
for l in range (0,n1):
for i in range(0,n1):
for j in range(i+l,n1+l):
for k in range(0,n2):
j = j % n1
line[k] += num[j][k]
if now_sum <0:
now_sum = 0
now_sum += line[k]
if now_sum > max_sum:
max_sum = now_sum
now_sum = 0
now_sum=0
line = [0]*n2
return max_sum def maxsum(num,n1,n2):#普通
line = [0]*n2
max_sum = 0 #最大和
now_sum = 0 #当前和
for i in range(0,n1):
for j in range(i,n1):
for k in range(0,n2):
line[k] += num[j][k]
if now_sum <0:
now_sum = 0
now_sum += line[k]
if now_sum > max_sum:
max_sum = now_sum
now_sum = 0
now_sum=0
line = [0]*n2
return max_sum def maxsum_vh(num,n1,n2):#垂直水平相连
line = [0]*n2
max_sum = 0 #最大和
now_sum = 0 #当前和
for l1 in range (0,n1):
for l2 in range (0,n2):
for i in range(0,n1):
for j in range(i+l1,n1+l1):
for k in range(0+l2,n2+l2):
j = j % n1
k = k % n2
line[k] += num[j][k]
if now_sum <0:
now_sum = 0
now_sum += line[k]
if now_sum > max_sum:
max_sum = now_sum
now_sum = 0
now_sum=0
line = [0]*n2
return max_sum def searchthrough(x,y,num,now_sum):#搜索函数
global max_sum,pointgroup,min_x,min_y,visited
max_sum = max(max_sum, now_sum)
for i in [[0,-1],[1,0],[0,1],[-1,0]]:
if x+i[0]>=min_x and x+i[0]<n1 and y+i[1]>=min_y and y+i[1]<n2 and visited[(x+i[0])%n1,(y+i[1])%n2]==0 and [(x+i[0])%n1,(y+i[1])%n2,num[(x+i[0])% n1][(y+i[1])%n2]] not in pointgroup:
pointgroup.append([(x + i[0]) % n1, (y + i[1]) % n2, num[(x + i[0]) % n1][(y + i[1]) % n2]])
if pointgroup == []:
return
pointgroup = sorted(pointgroup, key=lambda x: x[2])
nextpoint = pointgroup.pop()
if now_sum + nextpoint[2] > 0:
visited[nextpoint[0], nextpoint[1]] = 1
searchthrough(nextpoint[0],nextpoint[1],num,now_sum + nextpoint[2])
visited[nextpoint[0], nextpoint[1]] = 0
else:
return def maxsum_a(num,n1,n2): #连通
global min_x,min_y,max_sum,visited
min_x = 0
min_y = 0
max_sum = 0
now_sum = 0
startpointx = []
startpointy = []
pointgroup = []
for i in range(0,n1):
for j in range(0,n2):
visited[i,j] = 0
for i in range(0,n1):
for j in range(0,n2):
if num[i][j] > 0:
startpointx.append(i)
startpointy.append(j)
for pointx in startpointx:
pointy = startpointy.pop()
visited[pointx, pointy] = 1
searchthrough(pointx,pointy,num,num[pointx][pointy])
return max_sum def maxsum_vha(num,n1,n2): #水平垂直上相连 连通
global min_x,min_y,max_sum,visited
min_x = -n1
min_y = -n2
max_sum = 0
now_sum = 0
startpointx = []
startpointy = []
pointgroup = []
for i in range(0,n1):
for j in range(0,n2):
visited[i,j] = 0
for i in range(0,n1):
for j in range(0,n2):
if num[i][j] > 0:
startpointx.append(i)
startpointy.append(j)
for pointx in startpointx:
pointy = startpointy.pop()
visited[pointx, pointy] = 1
searchthrough(pointx,pointy,num,num[pointx][pointy])
return max_sum def main():
setglobalvar()
global n1,n2
max_sum = 0
V = H = A = False
if "\\v" in sys.argv[1:]:
V = True;
if "\\h" in sys.argv[1:]:
H = True;
if "\\a" in sys.argv[1:]:
A = True;
filename = sys.argv[-1];
try:
f = open(filename,"r")
except:
raise IOError("ERROR:can't open the file")
try:
line = f.readline()
line = line.strip('\n').strip(',')
n1 = int(line)
line = f.readline()
line = line.strip('\n').strip(',')
n2 = int(line)
num=[[]]*int(n1)
for i in range(0,int(n1)):
line = f.readline()
line = line.strip('\n')
if len(line.split(",")) != n2:
raise ValueError("ERROR:the format of file is wrong")
num[i] = line.split(",")
num=[[int(x) for x in inner] for inner in num]
except:
raise ValueError("ERROR:the format of file is wrong")
if V!=True and H!=True and A == True:#连通
max_sum = maxsum_a(num,n1,n2);
elif V==True and H!=True and A != True:#水平上相连
max_sum = maxsum_v(num,n1,n2);
elif V!=True and H==True and A != True:#垂直上相连
max_sum = maxsum_h(num,n1,n2);
elif V==True and H==True and A != True:#水平垂直上相连
max_sum = maxsum_vh(num,n1,n2);
elif V==True and H==True and A == True:#水平垂直上相连连通
max_sum = maxsum_vha(num,n1,n2);
else:#普通
max_sum = maxsum(num,n1,n2);
return max_sum if __name__ == '__main__':
print main()
单元测试
我大概明白单元测试的概念,但是本次问题很难被看做是一个模块,写单元测试的时候也无从下手,只是简单地测试了一下命令行参数的处理、以及样例的结果验证。
项目时间
PSP2.1 |
Personal Software Process Stages |
Time (%) Senior Student |
Planning |
计划 |
6 |
· Estimate |
· 估计这个任务需要多少时间 |
6 |
Development |
开发 |
80 |
· Analysis |
· 需求分析 (包括学习新技术) |
10 |
· Design Spec |
· 生成设计文档 |
0 |
· Design Review |
· 设计复审 (和同事审核设计文档) |
0 |
· Coding Standard |
· 代码规范 (为目前的开发制定合适的规范) |
0 |
· Design |
· 具体设计 |
15 |
· Coding |
· 具体编码 |
40 |
· Code Review |
· 代码复审 |
5 |
· Test |
· 测试(自我测试,修改代码,提交修改) |
10 |
Reporting |
报告 |
14 |
|
2 |
|
|
2 |
|
|
10 |
总结
由于进入大学之后没有搞过ACM,在解决这个问题的时候非常得吃力,对于群里大家提出的想法也只能是不明觉厉,希望能够在接下来的课程中多多提高吧。
homework-02 "最大子数组之和"的问题进阶的更多相关文章
- homework-01 "最大子数组之和"的问题求解过程
写在前面:我的算法能力很弱,并且也是第一次写博文,总之希望自己能在这次的课程中学到很多贴近实践的东西吧. 1.这次的程序是python写的,这也算是我第一次正正经经地拿python来写东西,结果上来说 ...
- 求一个二维整数数组最大子数组之和,时间复杂度为N^2
本随笔只由于时间原因,我就只写写思想了 二维数组最大子数组之和,可以 引用 一维最大子数组之和 的思想一维最大子数组之和 的思想,在本博客上有,这里就不做多的介绍了 我们有一个最初的二维数组a[n ...
- [LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- 求一个整数数组最大子数组之和,时间复杂度为N
#include<iostream.h> int main () { ]={-,-,-,-,-,-,-,-,-,-}; ],sum=; ;i<;i++) { ) { sum=b[i] ...
- homework-01 "最大子数组之和"的解决过程
看到这个题目,我首先想到就是暴力解决 求出所有的子数组的和,取出最大值即可 但其中是可以有优化的 如 子数组[3:6]可以用[3:5]+[6]来计算 即可以将前面的计算结果保留下来,减少后面的重复计算 ...
- [Swift]LeetCode325. 最大子数组之和为k $ Maximum Size Subarray Sum Equals k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- 最大子数组之和(N)
int maxSum(int *array, int n) { ]; ; ; ; i < n; i++) { ) newsum += array[i]; else newsum = array[ ...
- [LeetCode] Maximum Product Subarray 求最大子数组乘积
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- [LeetCode] Maximum Subarray 最大子数组
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
随机推荐
- python小问题记录:
numpy.chararray.flatten chararray.flatten(order='C') Return a copy of the array collapsed into one d ...
- LA 6047 Perfect Matching 字符串哈希
一开始我用的Trie+计数,但是不是计多了就是计少了,后来暴力暴过去的…… 看了别人的代码知道是字符串哈希,但是仍有几个地方不理解: 1.26^500溢出问题 2.没考虑哈希碰撞? 跪求指点! #in ...
- 查看局域网内某个ip的mac地址
首先需要ping一下对方的ip,确保本地的arp表中缓存对方的ip和mac的关系 C:\Windows\System32>ping 192.168.1.231 正在 Ping 192.168 ...
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.解决办法
刚刚更新AS到2.0版本,然后导入Api Demos的时候出现了这个错误. 解决办法:在AS的菜单栏,Tools->Android ->Enable ADB integration 勾选就 ...
- 用imagemagick和tesseract-ocr破解简单验证码
用imagemagick和tesseract-ocr破解简单验证码 Tesseract-ocr据说辨识程度是世界排名第三,可谓神器啊. 准备工作: 1.安装tesseract-ocr sudo apt ...
- noip2003提高组题解
这一年的前三题虽然难度不高,但是第二题极为繁琐,想在考场上用较短的时间拿到第二题的分数难上加难.所以必须要调整策略,争取拿其他三题的分数.第四题是比较普通的搜索题,分数比较好拿,但是很容易想成树形DP ...
- Oracle 手工清除回滚段的几种方法
关于回滚段的问题,之前也小整理过一个,参考: Current online Redo 和 Undo 损坏的处理方法 http://blog.csdn.net/tianlesoftware/articl ...
- TCP/IP详解学习笔记(3)-IP协议,ARP协议,RARP协议
把这三个协议放到一起学习是因为这三个协议处于同一层,ARP协议用来找到目标主机的Ethernet网卡Mac地址,IP则承载要发送的消息.数据链路层可以从ARP得到数据的传送信息,而从IP得到要传输的数 ...
- jquery加入购物车飞入的效果
主要原理是:点击当前图片的时候,复制(克隆)当前图片在当前位置,然后利用jQuery的animate()方法实现图像的飞入效果 效果预览:http://runjs.cn/detail/qmf0mtm1 ...
- Delphi ORD
//Char 类型与其编码值的转换:varb: Byte;c: Char;beginb := Ord('A'); {返回: 65}b := Ord(#65); {返回: 65}b := Ord ...