196. Matrix Multiplication
time limit per test: 0.50 sec.
memory limit per test: 65536 KB
Let us consider an undirected graph G = <V, E> 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). 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 test(s)
Input
4 4
1 2
1 3
2 3
2 4
Output
18
大意 : 给定n个点m条边的图,构造矩阵An*m表示第i个点是第j条边得端点,求A * A 的转置矩阵中所有项的和
思路 : An*m * A的转置m*n 在左右两边各乘一个单位向量 I1*n
即 I * A * A‘ * I = (I * A) *( A‘ * I) 得到一个(1*M)矩阵 * (M*1)矩阵,这个可以在O(M)的时间内解出
Code:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
#define foru(i, a, b) for (int i=a; i<=b; i++)
#define ford(i, a, b) for (int i=a; i>=b; i--)
#define N 11000
#define M 110000
int n, m;
int a[N], b[M], c[M];
int main(){
//freopen("I.txt", "r", stdin);
scanf("%d %d", &n, &m);
foru(i, 1, n){
int u, v;
scanf("%d %d", &u, &v);
b[i] = u; c[i] = v;
a[u] ++; a[v] ++;
}
int ans = 0;
foru(i, 1, m)
ans += a[b[i]] + a[c[i]];
printf("%d\n", ans);
return 0;
}