• C++实现离散数学的关系类,支持传递闭包运算


      
      Graph底层是一个int型二维数组,当进行addEdge操作时,相当于在关系图的相应位置打上记号。


    1
    #include <vector> 2 #include <cassert> 3 #include <iostream> 4 using namespace std; 5 class Graph{ 6 private: 7 int n; 8 int** graph; 9 public: 10 Graph(int n){ 11 this->n = n; 12 graph = new int*[n]; 13 for(int i=0;i<n;i++) 14 graph[i] = new int[n]; 15 for(int i=0;i<n;i++) 16 for(int j=0;j<n;j++) 17 graph[i][j] = 0; 18 } 19 void addEdge(int a,int b){ 20 assert(a>0&&a<=n); 21 assert(b>0&&b<=n); 22 if(connected(a-1,b-1)) 23 return; 24 graph[a-1][b-1] = 1; 25 } 26 void removeEdge(int a,int b){ 27 assert(a>0&&a<=n); 28 assert(b>0&&b<=n); 29 if(!connected(a,b)) 30 return; 31 graph[a-1][b-1] = 0; 32 } 33 bool connected(int a,int b){ 34 return graph[a][b]==1; 35 } 36 void plus(int a1,int b1,int a2,int b2){ 37 if(graph[a1][b1]==0) 38 graph[a1][b1]+=graph[a2][b2]; 39 else 40 return; 41 } 42 void display(){ 43 cout<<"Matrix Form:"<<endl; 44 for(int i=0;i<n;i++){ 45 for(int j = 0;j<n;j++) 46 cout<<graph[i][j]<<" "; 47 cout<<endl; 48 } 49 cout<<"Front: "; 50 for(int i=0;i<n;i++) 51 for(int j=0;j<n;j++){ 52 if(graph[i][j]) 53 cout<<"<"<<i+1<<","<<j+1<<"> "; 54 } 55 cout<<endl; 56 } 57 };
    58 // RelationShip关系类与Graph类建立起has-a的关系
    59 class RelationShip{ 60 private: 61 bool print; 62 int num_points; 63 Graph graph; 64 public: 65 RelationShip(int num):graph(num){ 66 print = true; 67 this->num_points = num; 68 } 69 70 void add_RS(int a,int b){ 71 graph.addEdge(a,b); 72 } 73 74 void remove_RS(int a,int b){ 75 graph.removeEdge(a,b); 76 } 77 78 void transfer(){ //将矩阵作传递化闭包运算 79 for(int i = 0;i<num_points;i++){ 80 for(int j = 0;j<num_points;j++){ 81 if(graph.connected(j,i)){ 82 for(int k = 0;k<num_points;k++) 83 graph.plus(j,k,i,k); 84 } 85 } 86 } 87 print = true; 88 } 89 90 void show(){ 91 graph.display(); 92 } 93 }; 94 95 int main(){ 96 cout<<"请输入你希望的元素个数:"<<endl; 97 int n; 98 while(cin>>n){ 99 RelationShip op = RelationShip(n); 100 int num; 101 cout<<"你想联系起多少对关系呢?"<<endl; 102 cin>>num; 103 while(num--){ 104 cout<<"请输入[1,"<<n<<"]之间的任意一对序偶"<<endl; 105 int a,b; 106 cin>>a>>b; 107 op.add_RS(a,b); 108 } 109 cout<<"你想进行传递闭包运算吗?(yes or no)"<<endl; 110 string s; 111 cin>>s; 112 if(s=="yes") 113 op.transfer(); 114 op.show(); 115 } 116 }

     基础数据结构是邻接矩阵

  • 相关阅读:
    Ubuntu 18.04 初始化(server版本 )
    named主从环境部署
    CentOS 源码安装svn
    端口状态
    进程状态
    top命令详解
    gitlab部署
    day16
    day15
    day14
  • 原文地址:https://www.cnblogs.com/1Kasshole/p/9010618.html
Copyright © 2020-2023  润新知