۰۶-اردیبهشت-۱۳۹۱, ۱۳:۳۷:۵۵
ماتريس اسپارس يا ماتريس خلوت
کد:
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
main()
{
int mat1[6][3],mat2[6][3],res[11][3];
clrscr();
mat1[0][0]=20;
mat1[0][1]=20;
cout<<"input number of values";
cin>>mat1[0][2];
for(int i=1;i<=mat1[0][2];i++)
{
cout<<"input row:";
cin>>mat1[i][0];
cout<<"input col:";
cin>>mat1[i][1];
cout<<"input value:";
cin>>mat1[i][2];
}
clrscr();
mat2[0][0]=20;
mat2[0][1]=20;
cout<<"input number of values";
cin>>mat2[0][2];
for(i=1;i<=mat2[0][2];i++)
{
cout<<"input row:";
cin>>mat2[i][0];
cout<<"input col:";
cin>>mat2[i][1];
cout<<"input value:";
cin>>mat2[i][2];
}
int j,k=1,sum;
i=j=1;
while(i<=mat1[0][2] && j<=mat2[0][2])
{
if(mat1[i][0]<mat2[j][0])
{
res[k][0]=mat1[i][0];
res[k][1]=mat1[i][1];
res[k][2]=mat1[i][2];
i++;
k++;
}
else if(mat2[j][0]<mat1[i][0])
{
res[k][0]=mat2[j][0];
res[k][1]=mat2[j][1];
res[k][2]=mat2[j][2];
j++;
k++;
}
else if(mat1[i][1]<mat2[j][1])
{
res[k][0]=mat1[i][0];
res[k][1]=mat1[i][1];
res[k][2]=mat1[i][2];
i++;
k++;
}
else if(mat2[j][1]<mat1[i][1])
{
res[k][0]=mat2[j][0];
res[k][1]=mat2[j][1];
res[k][2]=mat2[j][2];
j++;
k++;
}
else
{ sum=mat1[i][2]+mat2[j][2];
if(sum!=0)
{
res[k][0]=mat2[j][0];
res[k][1]=mat2[j][1];
res[k][2]=sum;
i++;
j++;
k++;
}
else
{ i++;
j++;
}
}
}
while(i<=mat1[0][2])
{
res[k][0]=mat1[i][0];
res[k][1]=mat1[i][1];
res[k][2]=mat1[i][2];
i++;
k++;
}
while(j<=mat2[0][2])
{
res[k][0]=mat2[j][0];
res[k][1]=mat2[j][1];
res[k][2]=mat2[j][2];
j++;
k++;
}
res[0][0]=20;
res[0][1]=20;
res[0][2]=k-1;
clrscr();
for(i=0;i<=res[0][2];i++)
{
for(j=0;j<3;j++)
cout<<setw(5)<<res[i][j];
cout<<endl;
}
}