flyod 求传递闭包 (离散数学及应用p638 26)
Write a program to implement Computing the Transitive Closure,and testing you program with p638 26 in the text book.
26. Use your Algorithm to find the transitive closures of these relations on {a, b, c, d, e}.
a) {(a, c), (b, d), (c, a), (d, b), (e, d)}
b) {(b, c), (b, e), (c, e), (d, a), (e, b), (e, c)}
c) {(a, b), (a, c), (a, e), (b, a), (b, c), (c,a), (c,b), (d,a),(e, d)}
d) {(a, e), (b, a), (b, d), (c,d), (d,a), (d, c), (e,a), (e,b),(e, c), (e, e)}
借助flyod算法,用第三个顶点更新R[i][j],
当R[i][k]&R[k][j]都为1时R[i][j]增加一条边
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<cstring> using namespace std; const int maxn = 100 + 5; int n,T; bool R[maxn][maxn],flag; void Init() { memset(R,0,sizeof(R)); flag=n=0; cout<<"Please enter how many elements there are in the relationship"<<endl; cin>>n; cout<<"Please enter the elements of the relationship"<<endl; for(int i=1;i<=n;i++) { char a,b; cin>>a>>b; R[a-'a'+1][b-'a'+1] = true; } } int main() { cout<<"Please enter the number of data sets"<<endl; cin>>T; while(T--) { Init(); for(int k=1;k<=5;k++) for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) R[i][j]|=R[i][k]&R[k][j];//flyod printf("the transitive closures of R is{"); for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) { if(R[i][j]) printf("(%c,%c)",i-1+'a',j-1+'a'); } printf("}\n"); } return 0; } /* 4 5 a c b d c a d b e d 6 b c b e c e d a e b e c 9 a b a c a e b a b c c a c b d a e d 10 a e b a b d c d d a d c e a e b e c e e */