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 = {ai,j}, such
that ai,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
ATA.
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
其实就是一个矩阵,自己乘自己,画图可以秒懂
java:
import java.util.*; import java.io.*; import java.math.*; public class Main{ static final int MAXN = 10000 + 5; static int [] mp = new int[MAXN]; public static void main(String [] agrv) throws IOException { //System.setIn(new FileInputStream(new File("D:" + File.separator + "imput.txt"))); Scanner cin = new Scanner(System.in); int N, M, u, v; while(cin.hasNext()){ N = cin.nextInt(); M = cin.nextInt(); Arrays.fill(mp, 1, N + 1, 0); for(int i = 1;i <= M ;i ++){ u = cin.nextInt(); v = cin.nextInt(); if(u == v) mp[v] ++; else { mp[v] ++; mp[u] ++; } } long ans = 0; for(int i = 1;i <= N;i ++){ ans += (long)mp[i] * mp[i]; } System.out.println(ans); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-09 03:33:39