• 两种矩阵转置的代码


    #include<stdio.h>
    #include<stdlib.h>
    
    //#define MAX_TERMS 101
    #define MAX_COL 50
    
    typedef struct
    {
    	int row;
    	int col;
    	int value;
    }term;
    
    //term a[MAX_TERMS];
    
    /*void transpose(term a[], term b[])
    {
    	int n,i,j,currentb;
    	n=a[0].value;
    	b[0].row=a[0].col;
    	b[0].col=a[0].row;
    	b[0].value=n;
    
    	if(n>0)
    	{
    		currentb=1;
    		for(i=0;i<a[0].col;i++)
    			for(j=1;j<=n;j++)
    				if(a[j].col==i)
    				{
    					b[currentb].row=a[j].col;
    					b[currentb].col=a[j].row;
    					b[currentb].value=a[j].value;
    					currentb++;
    				}
    	}
    }*/
    
    void fast_transpose(term a[], term b[])
    {
    	
    	int row_terms[MAX_COL],starting_pos[MAX_COL];
    	int i,j,num_cols=a[0].col,num_terms=a[0].value;
    	b[0].row=num_cols;
    	b[0].col=a[0].row;
    	b[0].value=num_terms;
    
    	if(num_terms>0)
    	{
    		for(i=0;i<num_cols;i++)
    			row_terms[i]=0;
    		for(i=1;i<=num_terms;i++)
    			row_terms[a[i].col]++;
    		starting_pos[0]=1;
    		for(i=1;i<num_cols;i++)
    			starting_pos[i]=starting_pos[i-1]+row_terms[i-1];
    		for(i=1;i<=num_terms;i++)
    		{
    			j=starting_pos[a[i].col]++;
    			b[j].row=a[i].col;
    			b[j].col=a[i].row;
    			b[j].value=a[i].value;
    		}
    	}
    }
    
    int main(int argc, char **argv)
    {
    	int i;
    	term a[9]={{6,6,8},{0,0,15},{0,3,22},{0,5,-15},{1,1,11},{1,2,3},{2,3,-6},{4,0,91},{5,2,28}};
    	term b[9];
    
    //	transpose(a,b);
            fast_transpose(a,b);
            
    	for(i=0;i!=9;++i)
    		printf("%5d %5d %5d 
    ",b[i].row,b[i].col,b[i].value);
    	printf("
    ");
    }

  • 相关阅读:
    hdu 3268 09 宁波 现场 I
    hdu 3697 10 福州 现场 H
    CodeForces Round #521 (Div.3) D. Cutting Out
    #Leetcode# 226. Invert Binary Tree
    zufe 蓝桥选拔
    #Leetcode# 100. Same Tree
    #Leetcode# 6. ZigZag Conversion
    PAT 1084 外观数列
    #Leetcode# 38. Count and Say
    #Leetcode# 22. Generate Parentheses
  • 原文地址:https://www.cnblogs.com/bzyzhang/p/5399632.html
Copyright © 2020-2023  润新知