//图算法
//题目:某社交网络中,给定一个用户列表和他们之间的好友关系,
// 求出具有最多共同好友的用户对。
//
//问题函数定义:
//
//cpp
//std::pair<int, int> maxCommonFriends(const std::vector<std::pair<int, int>>& friendships, int numUsers);
//裁判测试程序样例:
//
//cpp
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
using namespace std;
std::pair<int, int> maxCommonFriends(const std::vector<std::pair<int, int>>& friendships, int numUsers) {
vector<vector<int>> lj(numUsers);
for (int i = 0; i < friendships.size(); i++) {
lj[friendships[i].first].push_back(friendships[i].second);
lj[friendships[i].second].push_back(friendships[i].first);
}
int a, b;
int maxc=INT_MIN;
for (int i = 0; i < lj.size(); i++) {
for (int j = i+1; j < lj.size(); j++) {
int cout = 0;
for (int q = 0; q < lj[i].size(); q++) {
if (find(lj[j].begin(), lj[j].end(), lj[i][q])!=lj[j].end()) {
cout++;
}
}
if (find(lj[i].begin(), lj[i].end(), j) != lj[i].end()) {
cout++;
}
if (cout > maxc) {
a = i;
b = j;
maxc = cout;
}
}
}
return make_pair(a, b);
}
int main() {
std::vector<std::pair<int, int>> friendships = { {0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3} };
int numUsers = 4;
auto result = maxCommonFriends(friendships, numUsers);
std::cout << "User " << result.first << " and User " << result.second << " have the most common friends." << std::endl;
return 0;
}
//输入样例:
//
//friendships = { {0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3} }
//numUsers = 4
//输出样例:
//
//User 1 and User 2 have the most common friends.
某社交网络中,给定一个用户列表和他们之间的好友关系,// 求出具有最多共同好友的用户对。(转换成邻接表)
最新推荐文章于 2024-06-06 15:10:46 发布