码迷,mamicode.com
首页 > 其他好文 > 详细

堆栈队列和数组-三元组稀疏矩阵

时间:2014-09-26 21:34:08      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   for   sp   div   on   

#include<iostream>
#include <iomanip>
#include"windows.h"
using namespace std;
struct Tripple
{
    int x,y,value;
};
struct TrippleMatrix
{
    int r,c,cnt;
    Tripple* tripples;
};

TrippleMatrix* createTrippleMatrix(int r,int c,int maxCnt)
{
    TrippleMatrix* p = (TrippleMatrix*)malloc(sizeof(TrippleMatrix));
    p->r=r;
    p->c=c;
    p->cnt=0;
    p->tripples=new Tripple[maxCnt];
    return p;
}
TrippleMatrix* transpose(TrippleMatrix*  src)
{
    TrippleMatrix* ans =createTrippleMatrix(src->c,src->r,src->cnt);
    for(int i=1;i<=ans->r;i++)
    {
        for(int j=0;j<src->cnt;j++)
        {
            if(src->tripples[j].y==i)
            {
                Tripple newTripple;
                newTripple.x=i;
                newTripple.y=src->tripples[j].x;
                newTripple.value=src->tripples[j].value;
                ans->tripples[ans->cnt++]=newTripple;
            }
        }
    }
    return ans;
}
void output(TrippleMatrix* src)
{
    int cur=0;
    for(int i=1;i<=src->r;i++)
    {
        for(int j=1;j<=src->c;j++)
        {
            if(src->tripples[cur].x==i && src->tripples[cur].y==j)
            {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|FOREGROUND_GREEN);//彰显非0元
                cout<<src->tripples[cur].value<<"   ";
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);//设置三色相加
                cur++;
            }
            else cout<<"0   ";
        }
        cout<<endl;
    }
}
void main()
{
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);//设置三色相加
     int r=12,c=17,maxCnt=40;
     TrippleMatrix* m= createTrippleMatrix(r,c,maxCnt);
     for(int i=1;i<=r;i++)
     {
         for(int j=1;j<=c;j++)
         {
             if(rand()%10==1 && m->cnt<maxCnt)
             {
                 m->tripples[m->cnt].x=i;
                 m->tripples[m->cnt].y=j;
                 m->tripples[m->cnt].value=rand()%10;
                 m->cnt++;
             }
         }
     }
     output(m);
     cout<<endl;
     output(transpose(m));
     cin>>r;
}

 

堆栈队列和数组-三元组稀疏矩阵

标签:style   blog   color   io   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/kbyd/p/3995532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!