gpt4 book ai didi

c - tsp 使用动态规划

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:11 25 4
gpt4 key购买 nike

我正在使用一段代码来使用动态编程实现 TSP。我找到了这段代码,但无法弄清楚 compute() 函数及其工作原理。我不知道变量是什么,也不知道它是如何计算路径的。非常感谢任何帮助。

#include <stdio.h>
#include<limits.h>
#define size 10 //maximum 10 cities
#define min(a,b) a>b?b:a
#define sizePOW 1024
int n,npow,g[size][sizePOW],p[size][sizePOW],adj[size][size];
int compute(int start,int set)
{
int masked,mask,result=INT_MAX,temp,i,t1;//result stores the minimum
if(g[start][set]!=-1)//memoization DP top-down,check for repeated subproblem
return g[start][set];
for(i=0;i<n;i++)
{ //npow-1 because we always exclude "home" vertex from our set

t1=1<<i;
mask=(npow-1)-(1<<i);//remove ith vertex from this set
masked=set&mask;
if(masked!=set)//in case same set is generated(because ith vertex was not present in the set hence we get the same set on removal) eg 12&13=12
{
temp=adj[start][i]+compute(i,masked);//compute the removed set
if(temp<result)
result=temp,p[start][set]=i;//removing ith vertex gave us minimum
}
}
return g[start][set]=result;//return minimum
}

void TSP()
{
int i,j;
//g(i,S) is length of shortest path starting at i visiting all vertices in S and ending at 1
for(i=0;i<n;i++)
for(j=0;j<npow;j++)
g[i][j]=p[i][j]=-1;
for(i=0;i<n;i++){
g[i][0]=adj[i][0];//g(i,nullset)= direct edge between (i,1)
}

int result=compute(0,npow-2);//npow-2 to exclude our "home" vertex
printf("Tour cost:%d\n",result);
printf("Tour path:\n0 ");
getpath(0,npow-2);
printf("0\n");
}
int main(void) {
int i,j;
printf("Enter number of cities\n");
scanf("%d",&n);
npow=(int)pow(2,n);//bit number required to represent all possible sets
printf("npow = %d ",npow);
printf("\nEnter the adjacency matrix\n");

for(i=0;i<n;i++)for(j=0;j<n;j++){
scanf("%d",&adj[i][j]);}
TSP();

return 0;
}

最佳答案

//g(i,S) is length of shortest path starting at i visiting all vertices in S and ending at 1

这条评论很重要。

Image 当前我们处于“start”,我们访问的城市是“set”(以set的二进制表示),我们如何计算其他状态?

例如我们有一条边“start”->“i”,然后

if(masked!=set)//in case same set is generated(because ith vertex was not present in the    set hence we get the same set on removal) eg 12&13=12
{
temp=adj[start][i]+compute(i,masked);//compute the removed set
if(temp<result)
result=temp,p[start][set]=i;//removing ith vertex gave us minimum
}

这是计算状态 g[start][masked],使用 g[start][set] 和边缘 (start,i)

正如我们所见,作者使用递归和动态规划来解决问题。时间是 O(2^n * n^2)

关于c - tsp 使用动态规划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25322806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com