#include <iostream> #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 using namespace std; typedef char ElemType; typedef int Status; typedef struct AlgSysNode{ ElemType *elem; //元素數組首地址 ElemType **table; //運算表首地址 int length; //元素個數 }AlgSysNode,*AlgSystem; //創建代數系統 void createAlgSystem(AlgSystem &G,int n){ int i,j; G = (AlgSystem)malloc(n*sizeof(AlgSysNode)); if(!G) return; G->elem = (ElemType *)malloc(n*sizeof(ElemType)); if(!G->elem) return; for(i=0;i<n;i++){ printf("第%d個元素是:",i+1); cin>>G->elem[i]; } G->table = (ElemType **)malloc(n*sizeof(ElemType*)); if(!G->table) return; for(i=0;i<n;i++){ G->table[i] = (ElemType *)malloc(n*sizeof(ElemType)); for(j=0;j<n;j++){ printf("運算表中第%d行第%d個是:",i+1,j+1); cin>>G->table[i][j]; } } G->length = n; return; } //定位元素 int LocateVex(AlgSystem G,ElemType e){ int i; for(i=0;i<G->length;i++){ if(G->elem[i] == e) return i; } return -1; } //封閉性 Status IsClosed(AlgSystem G){ int i,j; for(i=0;i<G->length;i++){ for(j=0;j<G->length;j++){ if(LocateVex(G,G->table[i][j])==-1) return FALSE; } } return TRUE; } //結合性 Status IsCombined(AlgSystem G){ int i,j,k,m,n; for(i=0;i<G->length;i++){ for(j=0;j<G->length;j++){ for(k=0;k<G->length;k++){ m = LocateVex(G,G->table[i][j]); n = LocateVex(G,G->table[j][k]); if(G->table[m][k] != G->table[i][n]){ return FALSE; } } } } return TRUE; } //有幺元 Status IsExist_e(AlgSystem G,ElemType &e){ int i,j,k; for(i=0;i<G->length;i++){ for(j=0;j<G->length;j++){ if(G->table[i][j] != G->elem[j]) break; } if(j == G->length){ for(k=0;k<G->length;k++){ if(G->table[k][i] != G->elem[k]) break; } if(k == G->length){ e = G->elem[i]; return TRUE; } } } return FALSE; } //逆元 Status IsExistInverse_e(AlgSystem G,ElemType e){ int i,j; for(i=0;i<G->length;i++){ for(j=0;j<G->length;j++){ if(G->table[i][j] == e) break; } if(j == G->length) return FALSE; } return TRUE; } Status IsGroup(AlgSystem G){ ElemType e; return IsClosed(G) && IsCombined(G) && IsExist_e(G,e) && IsExistInverse_e(G,e); } int main(){ int n = 0; AlgSystem G; printf("代數系統中元素的個數:"); scanf("%d",&n); createAlgSystem(G,n); if(IsGroup(G)){ printf("該代數系統是羣"); }else{ printf("該代數系統不是羣") ; } return 0; }
測試結果: