Matrix

来源:互联网 发布:网络音乐排行榜 编辑:程序博客网 时间:2024/04/30 04:11

Description

To efficient calculate the multiplication of a sparse matrix is very useful in industrial filed. Let’s consider
this problem:
A is an N*N matrix which only contains 0 or 1. And we want to know the result of AAT.
Formally, we define B = AAT, Aij is equal to 1 or 0, and we know the number of 1 in matrix A is M
and your task is to calculate B.

Input

The input contains several test cases. The first line of input contains a integer C indicating the number
of the cases.
For each test case, the first line contains two integer N and M.
and each of next M lines contains two integer X and Y , which means Axyis 1.
N ≤ 100000, M ≤ 1000, C ≤ 10

Output

For each test case, it should have a integer W indicating how many element in Matrix B isn’t zero in one
line.

Sample Input

25 31 02 13 33 30 01 02 0

Sample Output

39

HINT

ATmeans the Transpose of matrix A, for more details, ATij= Aji.

eg:
if Matrix A is:

123

456

789

then the matrix ATis

147

258

369

----------------------------------------------------------------------------------------------------------------------------------------------------------

这道题目的意思是给一个N*N的矩阵。然后M个点,这些点上的值为1.然后让这个矩阵乘以其的转置最后得出来的矩阵之中有多少个一。
但是有一个问题就是你如果用二维数组来存的话,1000*1000=一百万。编译首先就过不去。所以我们
由题意可以得出当矩阵和它的转置a[i][k]==a[k][j]的时候的这个点必定为1,所以只要将这些点的X,Y反过来存。再比较
b[i]==c[k]是否相等。再将a[i]和d[k]存到结构体数组中,然后计数器累加就行了。但是这样的话会出现重复的点,所以必须对结果进行排序,去掉重复的点就OK了。
ps:由于不了解结构体排序所以就在排序那卡了一天的说。
 
#include<stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int a[1111],b[1111],c[1111],d[1111];struct node{    int x1,y1;}N[1000000];int cmp(const void *p1,const void *p2){        struct node *c=(node *)p1;        struct node *d=(node *)p2;        if(c->x1!=d->x1)                return c->x1-d->x1;        else                return c->y1-d->y1;}int main(){    int C,n,m;    int i,k;    int x,y,num,count;    cin>>C;    while(C--)    {        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        memset(c,0,sizeof(c));        memset(d,0,sizeof(d));        memset(N,0,sizeof(N));        cin>>n>>m;        for(i=0;i<m;i++)        {            cin>>x>>y;            a[i]=x;            b[i]=y;            c[i]=y;            d[i]=x;        }        num=0;count=0;        for(i=0;i<m;i++)            for(k=0;k<m;k++)                if(b[i]==c[k])                    {                        num++;                        N[count].x1=a[i];                        N[count].y1=d[k];                        count++;                    }        qsort(N,count,sizeof(N[0]),cmp);        count=num;        for(i=0;i<count-1;i++)                if(N[i].x1==N[i+1].x1&&N[i].y1==N[i+1].y1)                    num--;        cout<<num<<endl;    }   return 0;}

 

原创粉丝点击