题目:设A=(a1, a2, ... ,am)和B=(b1, b2, ... ,bn) 均为顺序表,A' 和B' 分别是除去最大公共前缀后的子表。如A= ('b', 'e', 'i', 'j', 'i', 'n', 'g'), B= ('b', 'e', 'i', 'f', 'a', 'n', 'g'), 则两者的最大公共前缀为'b', 'e', 'i', 在两个顺序表中除去最大公共前缀后的子表分别为A' =('j', 'i', 'n', 'g'), B' = ('f', 'a', 'n', 'g')。若A' = B' = 空表,则A = B; 若A' = 空表且B' ≠ 空表,或两者均不空且A'的第一个元素值小于B'的第一个元素的值,则A<B;否则A>B。编写一个算法,根据上述方法比较A和B的大小。
代码实现:
#include <iostream>
#include <cstdlib>
#define N 40001
using namespace std;
typedef int DataType;
typedef struct node1{
DataType a[N];
DataType lenth;
}LineList_1;
typedef struct node2{
DataType a[N];
DataType lenth;
}LineList_2;
void Init_List(LineList_1& L1, LineList_2& L2){
L1.lenth = 0;
L2.lenth = 0;
}
void Create_List(LineList_1& L1, LineList_2& L2){
int n;
cout << "请输入第一个要输入的序列个数:";
cin >> n;
cout << "请输入" << n << "个数字:";
for (int i = 0; i < n; i++){
cin >> L1.a[i];
}
L1.lenth = n;
cout << "请输入第二个要输入的序列个数:";
cin >> n;
cout << "请输入" << n << "个数字:";
for (int i = 0; i < n; i++){
cin >> L2.a[i];
}
L2.lenth = n;
}
int cmp(int a[], int a_len, int b[], int b_len){
// 优先比较值再比较长度
int min_len = a_len < b_len ? a_len : b_len;
for (int i = 0; i < min_len; i++)
if (a[i] != b[i]) return a[i] > b[i];
if (a_len != b_len) return a_len > b_len;
return -1;
}
int Deal(LineList_1& L1, LineList_2& L2){
int a_1[L1.lenth], a_2[L2.lenth];
int a_1_lenth = 0, a_2_lenth = 0;
int min_len = L1.lenth < L2.lenth ? L1.lenth : L2.lenth;
// 去除公共前缀
for (int i = 0; i <= min_len; i++){
if (L1.a[i] != L2.a[i]){
a_1[a_1_lenth++] = L1.a[i];
a_2[a_2_lenth++] = L2.a[i];
}
}
if (L1.lenth > L2.lenth)
while (a_1_lenth < L1.lenth)
a_1[a_1_lenth] = L1.a[a_1_lenth], a_1_lenth++;
return cmp(a_1, a_1_lenth, a_2, a_2_lenth);
}
int main(){
LineList_1 L1;
LineList_2 L2;
// 初始化序列
Init_List(L1, L2);
// 创建序列
Create_List(L1, L2);
//处理序列
if (Deal(L1, L2) == 1) cout << "A>B";
else if(Deal(L1, L2) == -1) cout << "A=B";
else cout << "A<B";
return 0;
}