最优配餐(bfs)
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述 栋栋最近开了一家餐饮连锁店,提供外卖服务。随着连锁店越来越多,怎么合理的给客户送餐成为了一个急需解决的问题。 输入格式 输入的第一行包含四个整数n, m, k, d,分别表示方格图的大小、栋栋的分店数量、客户的数量,以及不能经过的点的数量。 输出格式 输出一个整数,表示最优送餐方式下所需要花费的成本。 样例输入 10 2 3 3 样例输出 29 评测用例规模与约定 前30%的评测用例满足:1<=n <=20。 |
C++用bfs过了,python同样的思路超时,可能还有更好的方法,继续用py干。。
class node:
x=0
y=0
time=0
def bfs():
ans =0
cxf = node()
while len(queue)!=0:
cxf = queue[0]
queue.pop(0)
#print(2)
for i in range(4):
nd = node()
#print(3)
nd.x = cxf.x+dir[i][0]
nd.y = cxf.y+dir[i][1]
nd.time = cxf.time+1
if vis[nd.x][nd.y]==0 and nd.x>=1 and nd.x<=n and nd.y>=1 and nd.y<=n:
ans = ans + pay[nd.x][nd.y]*nd.time
vis[nd.x][nd.y]=1
queue.append(nd)
#print(2)
return ans
while True:
try:
dir = [[0]*2 for i in range(4)]
dir[0][1] = 1
dir[1][1] = -1
dir[2][0] = 1
dir[3][0] = -1
queue = []
#graph = [[] for i in range(1005)]
vis = [[0]*1005 for i in range(1005)]
pay = [[0]*1005 for i in range(1005)]
n,m,k,d = map(int,input().split())
for i in range(m):
x,y = map(int,input().split())
tmp = node() #坑死了,放外边是全局,放循环内是局部bl。。
tmp.x = x
tmp.y = y
tmp.time=0
queue.append(tmp) #所有起点加入队列,这样接下来就是每个起点出发bfs,都是往最近的客户那里找,所以bfs的结果最优
vis[x][y]=1
#print(len(queue))
#print(dir)
for i in range(k):
x,y,c = map(int,input().split())
pay[x][y]+=c #用个带权的邻接矩阵,同坐标多客户订餐累加即可,花费就是路径长乘以订餐数
for i in range(d):
x,y = map(int,input().split())
vis[x][y]=1
ans = bfs()
print(ans)
#queue[0].x=1
#print(queue[0].x)
except:
break