计算传递闭包

时间:2021-09-28 22:39:50
//沃舍尔算法计算传递闭包
//warshall:
//W=M
//for k=1 to n
//begin
// for i=1 to n
// begin
// for j=1 to n
// W(ij)=W(ij)+(W(ik)*W(kj))
// end
//end
//
//
#include <iostream>
using namespace std;
int v,edge;
int** draw();//绘图
void transitive(int **a);//计算


int main(int argc, char const *argv[])
{
int** a=draw();
transitive(a);

delete []a;
return 0;
}

int** draw()//绘图
{
int i,j;
cin>>v>>edge;///输入点数目和边数目

int **a=new int*[v];
for ( i = 0; i < v; ++i)
a[i]=new int[v];

for ( i = 0; i < v; ++i)
for ( j = 0; j < v; ++j)
a[i][j]=0;

int spot1,spot2;
for ( i = 0; i < edge; ++i)
{
cin>>spot1>>spot2;
a[spot1][spot2]=1;
}
///-------------------------------------------------------------///
cout<<"\n";
for ( i = 0; i < v; ++i)
{
for ( j = 0; j < v; ++j)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n";
return a;
}
void transitive(int **a)//计算
{
int i,j,k;
for ( k = 0; k < v; ++k)
{
for (i = 0; i < v; ++i)
{
for ( j = 0; j < v; ++j)
{
if (a[i][j] || (a[i][k] && a[k][j]))
{
a[i][j]=1;
}
}
}
}
for ( i = 0; i < v; ++i)
{ cout<<"\n";
for ( j = 0; j < v; ++j)
{
cout<<a[i][j];
}
}
}

3 5
0 0
0 2
1 1
2 0
2 1
1 0 1
0 1 0
1 1 0


111
010
111Press any key to continue
 
 
//计算传递闭包//R*=R1+R2+R3+....+Rn//Rn=Rn-1+R1//使用矩阵表示//算法://A=M//B=A//for(2 to n)//  begin//    A=A*M//    B=B+A//  end#include <iostream>using namespace std;int v,edge;int** draw();//绘图void transitive(int **a);//计算int main(int argc, char const *argv[]){	int** a=draw();	transitive(a);	delete []a;	return 0;}int** draw()//绘图  {    int i,j;    cin>>v>>edge;///输入点数目和边数目   int **a=new int*[v];  for ( i = 0; i < v; ++i)      a[i]=new int[v];    for ( i = 0; i < v; ++i)      for ( j = 0; j < v; ++j)        a[i][j]=0;      int spot1,spot2;    for ( i = 0; i < edge; ++i)    {      cin>>spot1>>spot2;      a[spot1][spot2]=1;  }  ///-------------------------------------------------------------///      	cout<<"\n";    for ( i = 0; i < v; ++i)    {  	    for ( j = 0; j < v; ++j)	    {	      cout<<a[i][j]<<" "; 	      }     cout<<"\n";      }      cout<<"\n";    return a;  }  void transitive(int **a)//计算{	int i,j,k,h; int **at=new int*[v];  for ( i = 0; i < v; ++i)      at[i]=new int[v];   int **bb=new int*[v];  for ( i = 0; i < v; ++i)      bb[i]=new int[v];    for ( i = 0; i < v; ++i)      for ( j = 0; j < v; ++j)        bb[i][j]=at[i][j]=a[i][j];   for ( i = 0; i < v-1; ++i)  {  	for ( j = 0; j < v; ++j)  		for ( k = 0; k < v; ++k)  	  			for ( h = 0; h < v; ++h) 			  				if (at[j][h]*a[h][k] == 1)at[j][k]=1;		////////if (at[j][h] && a[h][k])at[j][k]=1;    for ( k = 0; k < v; ++k)    	for ( h = 0; h < v; ++h)			if (bb[k][h]+at[k][h] >=1)//if (bb[k][h] || at[k][h])    			bb[k][h]=1;     }      for ( k = 0; k <v; ++k){      	cout<<"\n";    	for ( h = 0; h < v; ++h)    			cout<<bb[k][h];       	}}3 50 00 21 12 02 11 0 10 1 01 1 0111010111Press any key to continue