1. Problem description:
defines the distance D of the triplet (a, b, c) (a, b, c are all integers) = |a - b| + |b - c| + |c - a|. Given three flight control certificate sets S1, S2 and S3 are stored in 3 arrays in ascending order. Please design an algorithm as efficient as possible to calculate and output all possible triples (a, b, c) (a ∈ \in ∈S1,b ∈ \in ∈S2,c ∈ \in ∈S3) intermediate minimum distance. For example, S1 = {-1, 0, 9}, S2 = {-25, -10, 10, 11}, S3 = {2, 9, 17, 30, 41}, 则Minimum distance为2、Compatible ternary group (9, 10, 9). Request:
- The basic design ideas of the algorithm are given.
- According to the design idea, C language or C++ language is used to describe the algorithm, and comments are given on key points.
- Describe the time complexity and space complexity of the algorithm you designed.
2. Algorithmic thinking:
Analysis: From D = |a - b| + |b - c| + |c - a| >= 0, the following conclusion is drawn.
- When a = b = c, the distance is smallest.
- Other circumstances. Non-loss generality, calculation a <= b <= c, observation below:
L1 = |a - b|
L2 = |b - c|
L3 = |c - a|
D = |a - b| + |b - c| + | c - a| = L1 + L2 + L3 = 2L3 - It can be seen from the expression of D that in fact the key to determining the size of D is the distance between a and c, so the problem can be simplified to finding an a each time c is fixed, so that L3 = |c - a|Minimum.
- Use Dmin to record the minimum distance of all processed triples, and the initial value is a large enough integer.
- The set S1, S2 and S< /span>, end. min – output D – Add the subscript of the minimum value in A[i], B[j], C[k] by 1; (Control analysis: the minimum value is a, The maximum value is c, where c remains unchanged and a is updated, trying to find a smaller distance D) = D; (Update D)min, then Dmin – If D<D – Calculate the distance D of (A[i], B[j], C[k]); (calculate D) | (|S| represents the number of elements in the set S number), perform the following steps in a loop: 3| and k<|S2|, j<|S1 are stored in arrays A, B, and C respectively. The subscript variable of the array i = j = k = 0, when i<|S3
3. Algorithm code:
#define INT_MAX 0X7fffffff
int abs_(int a)//计算绝对值
{
if(a < 0)
return -a;
else
return a;
bool xls_min(int a,int b,int c)//a是否是三个数中的最小值
{
if(a <= b && a <= c)
return true;
return false;
}
int findMinofTrip(int A[],int n, int B[],int m,int C[],int p)
//D_min用于记录三元组的最小距离,初值赋为INT_MAX
{
int i = 0,j = 0,D_min = INT_MAX,D;
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]);//计算D
if(D < D_min)//更新D
D_min = D;
if(xls_min(A[i],B[j],C[k]))//更新a
i++;
else
{
if(xls_min(B[j],C[k],A[i]))
j++;
else
k++;
}
}
return D_min;
}
}
3. Algorithm complexity:
设n = (|S1| + |S2| + |S3|)
- Time complexity: O(n).
- Space complexity: O(1).