本题其实就是找a到c的最小值
有讲解p19 第14题 c语言实现王道数据结构课后代码题_哔哩哔哩_bilibili
下方有图:
本题代码如下
int abs(int a)//计算绝对值
{if (a < 0)return -a;elsereturn a;
}
int min(int a, int b, int c)//a是否为三个数中的最小值
{if (a <= b && a <= c)return 1;elsereturn 0;
}
int findmin(int a[], int m, int b[], int n, int c[], int p)
{int i = 0;int j = 0;int k = 0;int d_min = max;//用来记录三元组中的最小距离,初值赋为maxint d = 0;while (i < n && j < m && k < p && d_min>0){d = abs(a[i]-b[j])+abs(b[j]-c[k])+abs(c[k]-a[i]);if (d < d_min){d_min = d;}if (min(a[i], b[j], c[k]))//更新ai++;else if (min(b[j], c[k], a[i]))//更新bj++;else//更新ck++;}return d_min;
}
完整测试代码
#include<stdio.h>
#define max 0x7fffffff
int a[3] = { -1,0,9 };
int m = 3;
int b[4] = { -25,-10,10,11 };
int n = 4;
int c[5] = { 2,9,17,30,41 };
int p = 5;
int abs(int a)//计算绝对值
{if (a < 0)return -a;elsereturn a;
}
int min(int a, int b, int c)//a是否为三个数中的最小值
{if (a <= b && a <= c)return 1;elsereturn 0;
}
int findmin(int a[], int m, int b[], int n, int c[], int p)
{int i = 0;int j = 0;int k = 0;int d_min = max;//用来记录三元组中的最小距离,初值赋为maxint d = 0;while (i < n && j < m && k < p && d_min>0){d = abs(a[i]-b[j])+abs(b[j]-c[k])+abs(c[k]-a[i]);if (d < d_min){d_min = d;}if (min(a[i], b[j], c[k]))//更新ai++;else if (min(b[j], c[k], a[i]))//更新bj++;else//更新ck++;}return d_min;
}
int main()
{int ret = findmin(a, m, b, n, c, p);printf("%d", ret);
}