There is a group of n people indexed by positive integers from 1 to n forming a network of friendship.
Friendship of x and y is denoted by a pair(x,y), which means x and y are friends.
If x is friend of y and y is friend of z , z is friend of friend of x.
We'd like to find out maximal sum of friends of friends of people among the group.
Input Format
The first line is n .
The second line is m , which is number of friend-pairs in the network of friendship.
The following m lines are friend-pairs.
Sample Input 0
5
6
1 2
1 3
2 3
2 4
3 5
4 5
Sample Output 0
14
The code below is the answer, but I got a hard time understanding why is there a u--, v--; in line 8
and also, what is the meaning of line 16~22, is that what we should usually do to an adjacency list?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m; cin >> n >> m;
// adjacency list
vector<vector<int>> graph(n);
for (int i = 0; i < m; i++) {
int u, v; cin >> u >> v; u--, v--;
graph[u].emplace_back(v);
graph[v].emplace_back(u);
}
int ans = 0;
for (int i = 0; i < n; i++) {
vector<bool> vis(n, false);
for (auto u : graph[i]) {
for (auto v : graph[u]) {
vis[v] = true;
}
}
int sum = 0;
vis[i] = false;
for (int j = 0; j < n; j++) {
if (vis[j]) sum += j+1;
}
ans = max(sum, ans);
}
cout << ans << endl;
}
|