SGU-196-Matrix Multiplication (Matrix Multiplication)
196. Matrix Multiplicationtime limit per test: 0.25 sec.
Memory limit per test: 65536 KB input: standard
Output: standard
Let us consider an undirected graph G = Which has N vertices and M edges. incidence matrix of this graph is an N × M matrix A = {aij }, such that aij 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 where AT is A transposed, I. e. an M × N matrix obtained from A by turning its columns to rows and vice versa.
Input
The first line of the input file contains two integer numbers-N and M (2 le N le 10,000, 1 le M le 100,000 ). 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 test (s)
Input
4 4 1 2 1 3 2 2 4 Output
18
[Submit] [forum]
Author: |
Andrew Stankevich, Georgiy Korneev |
Resource: |
Petrozavodsk Winter Trainings 2003 |
Date: |
2003- |
Idea: manually execute a few times to find the law. Here, the method for storing the edges in the graph is a fully correlated matrix (introduced in discrete mathematics ), the rule of this question is to count the square of the number of occurrences of each fixed point.
AC code:
#include
#include
#include
#include #define LL long longusing namespace std;int num[10005];int N, M;int main() {while(scanf("%d %d", &N, &M) != EOF) {memset(num, 0, sizeof(num));for(int i = 0; i < M; i++) {int a, b;scanf("%d %d", &a, &b);num[a]++, num[b]++;}LL ans = 0;for(int i = 1; i <= N; i++) {ans += (num[i] * num[i]);}cout << ans << endl;}return 0;}