题目描述:
Problem Description
Let us consider undirected graph G = {V; E} which has N vertices and M edges. Incidence matrix of this graph is N × M matrix A = {ai,j}, such that ai,j 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 ATA.
Input
The first line of the input file contains two integer numbers — N and M (2 ≤ N ≤ 10 000, 1 ≤ M ≤100 000). Then 2*M 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
4 4
1 2
1 3
2 3
2 4
Sample Output
18
题目分析:
一看题目,矩阵乘法,会不会想到矩阵快速幂或者其他数学算法呢?其实这题并不是。当时做这道题就感觉这题很难看懂,矩阵的转置与矩阵相乘,但是矩阵乘法的出来不应该是一个矩阵吗?怎么变成一个数了?
给一个n个顶点,m条边的无向图,若i与j有边,将矩阵元素ij加一。
因为这题是无向图,所以这个矩阵应该是对称阵,所以其转置就等于本身,所以这题的矩阵相乘其实求的是矩阵的平方和。
于是,将每一个顶点的度数求平方和,就是本题答案。(这样看起来好水有没有)
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n,m;
int deg[10010];
long long ans;
int main()
{
while(scanf("%d%d",&n,&m)!=-1)
{
ans=0;
memset(deg,0,sizeof(deg));
for(int i=1; i<=m; i++)
{
int a,b;
scanf("%d%d",&a,&b);
deg[a]++;
deg[b]++;
}
for(int i=1; i<=n; i++)
{
ans+=deg[i]*deg[i];
}
printf("%lld\n",ans);
}
return 0;
}