Matrix

来源:互联网 发布:json是用来干嘛的 编辑:程序博客网 时间:2024/04/30 02:06

To ecient calculate the multiplication of a sparse matrix is very useful in industrial led. 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 de ne 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 rst line of input contains a integer C indicating the number
of the cases.
For each test case, the rst line contains two integer N and M.
and each of next M lines contains two integer X and Y , which means Axy is 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 and output
stdin stdout
2
5 3
1 0
2 1
3 3
3 3
0 0
1 0
2 0

stdout
3
9
源代码:

#include<cstdio>
#include<algorithm>
using namespace std;
#define N 1000000+10
#define M 1000+10
struct node
{
 int x,y;
}s[N],a[M],aT[M];
bool cmp(node a,node b)
{
 if(a.x==b.x)
  return a.y>b.y;
 return a.x>b.x;
}
int main()
{
 int cas,i,j,k,n,m;
 scanf("%d",&cas);
 while(cas--){
  int ans=0;
  scanf("%d%d",&n,&m);
  for(i = 0;i < m;i++)
  {
   scanf("%d%d",&a[i].x,&a[i].y);
   aT[i].x=a[i].y;
   aT[i].y=a[i].x;
  }
  int num = 0;
  for(i = 0;i < m;i++){
   for(j = 0;j < m;j++)
    if(a[i].y == aT[j].x){
     s[num].x = a[i].x;
     s[num++].y = aT[j].y;
    }
  }
  sort(s,s+num,cmp);
  for(i = 0;i < num;i++){
   if(s[i].x!=s[i+1].x||s[i].y!=s[i+1].y||i==num-1)
    ans++;
  }
  printf("%d\n",ans);
 }
 return 0;
}

原创粉丝点击