Matrix Multiplication
Time Limit:
2000/1000MS (Java/Others)
Memory Limit:
128000/64000KB (Java/Others)
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 = {a
i,j}, such that a
i,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 A
TA.
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
解决方案:此题可观察规律:每个a[i,j]都要乘上所有的a[j,k]。
code:#include <iostream> #include<cstdio> #include<cstring> #include<vector> using namespace std; const int maxn=10005; vector<int>G[maxn]; int main() { int n,m; while(~scanf("%d%d",&n,&m)){ for(int i=1;i<=n;i++) G[i].clear(); for(int i=1;i<=m;i++){ int a,b; scanf("%d%d",&a,&b); G[a].push_back(b); G[b].push_back(a); } int cnt=0; for(int i=1;i<=n;i++){ int len=G[i].size(); for(int j=0;j<len;j++){ cnt+=G[G[i][j]].size(); } } printf("%d\n",cnt); } return 0; }