首页 > 其他分享 >数学建模习题6.2

数学建模习题6.2

时间:2024-10-14 23:45:11浏览次数:6  
标签:city parent weight self 建模 edges 6.2 习题 root

edges = [
("Pe", "T", 13),
("Pe", "N", 68),
("Pe", "M", 78),
("Pe", "L", 51),
("Pe", "Pa", 51),
("T", "N", 68),
("T", "M", 70),
("T", "L", 60),
("T", "Pa", 61),
("N", "M", 21),
("N", "L", 35),
("N", "Pa",36),
("M", "L", 56),
("M", "Pa", 57),
("L", "Pa", 21),
]
class UnionFind:
def init(self, n):
self.parent = list(range(n))
self.rank = [0] * n

def find(self, u):  
    if self.parent[u] != u:  
        self.parent[u] = self.find(self.parent[u])  
    return self.parent[u]  

def union(self, u, v):  
    root_u = self.find(u)  
    root_v = self.find(v)  
    if root_u != root_v:  
        if self.rank[root_u] > self.rank[root_v]:  
            self.parent[root_v] = root_u  
        elif self.rank[root_u] < self.rank[root_v]:  
            self.parent[root_u] = root_v  
        else:  
            self.parent[root_v] = root_u  
            self.rank[root_u] += 1  

def kruskal(edges):
edges.sort(key=lambda edge: edge[2])
uf = UnionFind(len(set(city for edge in edges for city in edge[:2])))
mst = []

for u, v, weight in edges:  
    if uf.find(u) != uf.find(v):  
        uf.union(u, v)  
        mst.append((u, v, weight))  
  
return mst  

city_map = {
"Pe": 0, "T": 1, "N": 2, "M": 3, "L": 4, "Pa": 5
}

edges_with_indices = [(city_map[u], city_map[v], weight) for u, v, weight in edges]

mst_edges = [(list(city_map.keys())[u], list(city_map.keys())[v], weight) for u, v, weight in kruskal(edges_with_indices)]

print("最小生成树的边:")
for u, v, weight in mst_edges:
print(f"{u} - {v}: {weight}")

print("2023310143005")

标签:city,parent,weight,self,建模,edges,6.2,习题,root
From: https://www.cnblogs.com/vvlin/p/18466489

相关文章

  • 数学建模习题6.3
    importheapqdefprim(graph,start):num_nodes=len(graph)visited=[False]*num_nodesmin_heap=[(0,start,-1)]mst_cost=0mst_edges=[]whilemin_heap:weight,u,parent=heapq.heappop(min_heap)ifvisited[u]:continue......
  • 数学建模习题5.4
    importnumpyasnpfromscipy.optimizeimportminimizedefobjective(x):return-np.sum(np.sqrt(x)*np.arange(1,101))defconstraint1(x):returnx[1]-10defconstraint2(x):return20-(x[1]+2*x[2])defconstraint3(x):return30-(x[1]+2x[2]+3x......
  • 数学建模习题5.5
    importnumpyasnpfromscipy.optimizeimportminimizedefobjective(x):return2x[0]+3x[0]2+3*x[1]+x[1]2+x[2]defconstraint1(x):return10-(x[0]+2x[0]**2+x[1]+2x[1]**2+x[2])defconstraint2(x):return50-(x[0]+x[0]2+x[1]+x[1]2......
  • 数学建模习题5.7
    total_demand=sum(demands)dp=np.full((4,total_demand+1),float('inf'))dp[0][0]=0prev_production=np.full((4,total_demand+1),-1)foriinrange(1,4):prev_demand=sum(demands[:i-1])forjinrange(total_demand+1):ifj<pr......
  • 数学建模习题4.4
    `MAX_B=24MAX_DEBUG=5products=[{"name":"Ⅰ","A_hours":1,"B_hours":6,"debug_hours":1,"profit":2},#假设产品Ⅰ至少使用1小时设备A{"name":"Ⅱ","A_hours":5,"......
  • 数学建模习题3.3
    importnumpyasnpfromscipy.sparse.linalgimporteigsimportpylabaspltw=np.array([[0,1,0,1,1,1],[0,0,0,1,1,1],[1,1,0,1,0,0],[0,0,0,0,1,1],[0,0,1,0,0,1],[0,0,1,0,0,0]])r=np.sum(w,axis=1,keepdims=True)n=w.sha......
  • 数学建模习题2.4
    importnumpyasnpimportmatplotlib.pyplotasplt定义x的范围x=np.linspace(-10,10,400)创建一个2行3列的子图布局fig,axs=plt.subplots(2,3,figsize=(12,8))遍历每个子图fork,axinenumerate(axs.flat,start=1):y=k*x**2+2*kax.plot(x,y,label......
  • 数学建模习题2.6
    importnumpyasnpimportmatplotlib.pyplotaspltfrommpl_toolkits.mplot3dimportAxes3D模拟高程数据(假设数据已经过某种方式插值或生成)这里我们创建一个简单的40x50网格,并填充随机高程值x=np.linspace(0,43.65,40)y=np.linspace(0,58.2,50)X,Y=np.meshgr......
  • 数学建模习题2.5
    importnumpyasnpimportmatplotlib.pyplotaspltfrommpl_toolkits.mplot3dimportAxes3D定义参数u和vu=np.linspace(-2,2,400)v=np.linspace(0,2*np.pi,400)U,V=np.meshgrid(u,v)根据参数方程计算x,y,zx=np.sqrt(1+U2+V2)*np.cos(V)y=np......
  • 数学建模习题2.8
    importnumpyasnp初始化系数矩阵A和常数项向量bn=1000A=np.zeros((n,n))b=np.arange(1,n+1)填充系数矩阵Aforiinrange(n):A[i,i]=4#对角线元素为4ifi<n-1:A[i,i+1]=1#每一行的下一个元素为1ifi>0:A[i,i-1]=1#每一行的上一个元素......