Matrix Multiplication(zoj 2316)

来源:互联网 发布:收看tvb电视软件 编辑:程序博客网 时间:2024/05/19 19:56
Matrix Multiplication(zoj   2316)


Let us consider undirected graph G =  which has N vertices and M edges. Incidence matrix of this graph is N * M matrix A = {a ij}, such that a ij is 1 if i-th vertex is one of the ends of j-th edge and 0 in the other case. Your task is to find the sum of all elements of the matrix A TA. 




This problem contains multiple test cases!
 
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.


The output format consists of N output blocks. There is a blank line between output blocks.


Input


The first line of the input file contains two integer numbers - N and M (2 <= N <= 10 000, 1 <= M <= 100 000). 2M integer numbers follow, forming M pairs, each pair describes one edge of the graph. All edges are different and there are no loops (i.e. edge ends are distinct).


Output


Output the only number - the sum requested.


Sample Input


1


 4 4
 1 2
 1 3
 2 3
 2 4




Sample Output


18




题目意思:有 N 个 点,M 条 边。需要构造一个N * M 大小的矩阵A。对于 (i, j) 这个坐标点它表示,对编号为 i 这个点编号为 j 的 点与它相连,此时标记(i, j) 为1,如果坐标点没有跟这条 j 的边相连,就标记为0。构造完这个矩阵A之后,需要求出它的转置矩阵AT,算出 ATA 的和。
题解:题意转化后,就是计算途中有多少条,长度为2的路径。注意是无向图。每个顶点,看它的度是多少。从这些度里面选取2个的组合数。

矩阵与矩阵相乘 
第一个矩阵的列数一必须等于第二个矩阵的行数 假如第一个是m*n的矩阵 第二个是n*p的矩阵 则结果就是m*p的矩阵 且得出来的矩阵中元素具有以下特点:
第一行第一列元素为第一个矩阵的第一行的每个元素和第二个矩阵的第一列的每个元素乘积的和 以此类推 第i行第j列的元素就是第一个矩阵的第i行的每个元素与第二个矩阵第j列的每个元素的乘积的和


#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<cstdlib>#include<algorithm>#define maxn 100005using namespace std;int a[maxn],b[maxn],f[11000];int main(){    int t,a,b,n,m,ans;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        memset(f,0,sizeof(f));        for(int i=0;i<m;i++)        {            scanf("%d%d",&a,&b);            ++f[a];            ++f[b];        }        ans=0;        for(int i=0;i<m;i++)            ans+=f[i]*(f[i]-1)/2;        ans=(ans+m)<<1;        printf("%d\n",ans);        if(t)            puts("");    }    return 0;}



0 0
原创粉丝点击