dist函数c语言 dist c语言

C语言实现最短路问题的算法#i ncludestdio.h
#i nclude stdlib.h
//Dijkstra算法实现函数
void Dijkstra(int n,int v,int dist[],int prev[],int **cost)
{
int i;
int j;
int maxint = 65535;//定义一个最大dist函数c语言的数值dist函数c语言,作为不相连dist函数c语言的两个节点的代价权值
int *s ;//定义具有最短路径的节点子集s
s = (int *)malloc(sizeof(int) * n);
//初始化最小路径代价和前一跳节点值
for (i = 1; i = n; i++)
{
dist[i] = cost[v][i];
s[i] = 0;
if (dist[i] == maxint)
{
prev[i] = 0;
}
else
{
prev[i] = v;
}
}
dist[v] = 0;
【dist函数c语言 dist c语言】s[v] = 1;//源节点作为最初的s子集
for (i = 1; in; i++)
{
int temp = maxint;
int u = v;
//加入具有最小代价的邻居节点到s子集
for (j = 1; j = n; j++)
{
if ((!s[j])(dist[j]temp))
{
u = j;
temp = dist[j];
}
}
s[u] = 1;
//计算加入新的节点后dist函数c语言,更新路径使得其产生代价最短
for (j = 1; j = n; j++)
{
if ((!s[j])(cost[u][j]maxint))
{
int newdist = dist[u] + cost[u][j];
if (newdistdist[j])
{
dist[j] = newdist;
prev[j] = u;
}
}
}
}
}
//展示最佳路径函数
void ShowPath(int n,int v,int u,int *dist,int *prev)
{
int j = 0;
int w = u;
int count = 0;
int *way ;
way=(int *)malloc(sizeof(int)*(n+1));
//回溯路径
while (w != v)
{
count++;
way[count] = prev[w];
w = prev[w];
}
//输出路径
printf("the best path is:\n");
for (j = count; j = 1; j--)
{
printf("%d - ",way[j]);
}
printf("%d\n",u);
}
//主函数,主要做输入输出工作
void main()
{
int i,j,t;
int n,v,u;
int **cost;//代价矩阵
int *dist;//最短路径代价
int *prev;//前一跳节点空间
printf("please input the node number: ");
scanf("%d",n);
printf("please input the cost status:\n");
cost=(int **)malloc(sizeof(int)*(n+1));
for (i = 1; i = n; i++)
{
cost[i]=(int *)malloc(sizeof(int)*(n+1));
}
//输入代价矩阵
for (j = 1; j = n; j++)
{
for (t = 1; t = n; t++)
{
scanf("%d",cost[j][t]);
}
}
dist = (int *)malloc(sizeof(int)*n);
prev = (int *)malloc(sizeof(int)*n);
printf("please input the source node: ");
scanf("%d",v);
//调用dijkstra算法
Dijkstra(n, v, dist, prev, cost);
printf("*****************************\n");
printf("have confirm the best path\n");
printf("*****************************\n");
for(i = 1; i = n ; i++)
{
if(i!=v)
{
printf("the distance costfrom node %d to node %d is %d\n",v,i,dist[i]);
printf("the pre-node of node %d is node %d \n",i,prev[i]);
ShowPath(n,v,i, dist, prev);
}
}
}
c语言中dist函数怎么用C语言的math库中提供了很多数学函数 , 其中包括计算两点之间距离的dist函数 。要使用该函数,需要在程序中引用math.h头文件,然后使用函数原型:double dist(double x1, double y1, double x2, double y2) 。其中 , x1和y1是第一个点的坐标,x2和y2是第二个点的坐标 。函数返回两点之间的距离 , 即勾股定理中的直线长度 。使用方法如下:
#include stdio.h
#include math.h
int main()
{
double x1 = 0, y1 = 0, x2 = 3, y2 = 4;
double distance = dist(x1, y1, x2, y2);
printf("Distance between (%.2f, %.2f) and (%.2f, %.2f) is %.2f

推荐阅读