ACdream 1213 Matrix Multiplication 其实是一道思维题

题目描述:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值