对三角矩阵进行压缩存储为一维数组

/*1.  已知矩阵A[5][5]是一个下三角矩阵,如下图
要求编写算法把矩阵A采用压缩存储,存储到一维数组B[16]中,
并且依次输出B中各元素的值以验证该算法功能已实现
*/
#include<iostream>
using namespace std;
const int m=5;
const int n=5; 
const int c=16;
int B[c];               //定义一维数组B[16],长度为16
//初始化数组A[5][5]
int A[m][n]={{1},{4,7},{6,9,5},{1,8,4,1},{2,3,0,9,6}};
int main()
{
	int i,j;
	int k;
	cout<<"输出二维数组的三角矩阵:"<<endl;
	for(i=0;i<m;i++)  //输出二维数组A的矩阵
		{
			for(j=0;j<n;j++)
			cout<<A[i][j]<<" ";
			cout<<endl;
	}
	cout<<endl;
	//对三角矩阵进行压缩
	for(i=0;i<m;i++)                //遍历三角矩阵
		{
			for(j=0;j<n;j++)
			if(i>=j)				//如果行号大于等于列号
			{   
				k=i*(i+1)/2+j;		//求出各元素的下标

				B[k]=A[i][j];		//存储元素
				
			}
			else					//如果行号小于列号
			{
				k=c-1;				//将元素下标定为c-1
				B[k]=0;				//元素的值存储为0
			}
			
	}
	cout<<"输出三角矩阵压缩后的一维矩阵:"<<endl;
		for(k=0;k<c;k++)					//按顺序输出压缩后的元素
		cout<<B[k]<<" ";
		cout<<endl;
	    system("pause");
		return 0;
}


posted on 2011-11-16 09:32  1.曲待续  阅读(1267)  评论(0编辑  收藏  举报

导航