1. 程式人生 > >C++實現離散數學的關系類,支持傳遞閉包運算

C++實現離散數學的關系類,支持傳遞閉包運算

nts bsp ostream oid 之間 end c++ ati AI

  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 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 }

C++實現離散數學的關系類,支持傳遞閉包運算