ZOJ - 2316 Matrix Multiplication

本文探讨了一个图论问题,即如何通过构建图的邻接矩阵并计算该矩阵与其转置的乘积来解决特定求和问题。文章提供了一个简洁高效的算法实现,并附带示例输入输出以帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Let us consider undirected graph G = which has N vertices and M edges. Incidence matrix of this graph is N * M matrix A = {aij}, 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 ATA.


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条边,建成一个矩阵,问这个矩阵和他的转置矩阵的乘积。

思路:例如样例,建成的矩阵是  0 1 1 0

                                                      1 0 1 1

                                                      1 1 0 0

                                                      0 1 0 0

乘以它的转置相当于乘它本身,a[1][2]这个数要和a[2][1],a[2][3],a[2][4]相乘得3个1,a[3][2],a[4][2]同理

每个矩阵位置为1的都可以这样计算,得出规律了

#nclude<iostream>

#include<cstdio>
#include<cstring>
using namespace std;
int main(){
    int a[10005];
    int t,n,m;
    int x,y,i;
    scanf("%d",&t);
    while(t--){
        memset(a,0,sizeof(a));
        scanf("%d%d",&n,&m);
        while(m--){
            scanf("%d%d",&x,&y);
            a[x]++;
            a[y]++;
        }
        int sum=0;
        for(i=1;i<=n;i++)
            sum+=a[i]*a[i];
        if(t==0)
            printf("%d\n",sum);
        else
            printf("%d\n\n",sum);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值