H - Matrix Multiplication ZOJ - 2316

本文介绍了一种通过构建无向图的邻接矩阵并利用矩阵运算来高效解决特定图论问题的方法。具体地,该文详细阐述了如何计算任意两点间路径数量的问题,并给出了一段C++代码实现。

摘要生成于 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 = {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个点的无向图,建立一个n*n的矩阵A,aij表示i点到j点是否有路,如果有路aij为1,否则为0,计算矩阵A^{\Gamma }*A中所有元素的和。因为是无向图,如果i点到j点有路,则j点到i点必定有路,所以矩阵A为对称矩阵。则A^{\Gamma }*A=A*A=\sum_{i=1}^{n}(\sum_{j=1}^{n} (\sum_{k=1}^{n} \underset{ij\,jk}{a\, a}))。aijajk是从i点到j点再到k点,只有当i到j有路,j到k有路时aijajk才为1,所以我们可以把问题转化为求从任意点出发走两步到任意点的方案数。这样这个问题就好解决了,假设有m条路连接i点,那么就有m总方法走一步到i点,又有m总方法走一步从i点到其他点,所以以i点为中转我们有m*m总走法,所以我们只需要计算每个点所连接的路的数量的平方和就可以得到问题的答案。

#include<iostream>
#include<cstring>
using namespace std;
int zu[10005];
int main()
{
    int t;
    cin>>t;
    while(t--){
        memset(zu,0,sizeof(zu));
        int n,m,a,b;
        cin>>n>>m;
        for(int i=1;i<=m;i++){
            cin>>a>>b;
            zu[a]++,zu[b]++;
        }
        int sum=0;
        for(int i=1;i<=n;i++){
            sum+=zu[i]*zu[i];
        }
        cout<<sum<<endl;
        if(t!=0)
            cout<<endl;
    }
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值