某社交网络中,给定一个用户列表和他们之间的好友关系,// 求出具有最多共同好友的用户对。(转换成邻接表)

//图算法
//题目:某社交网络中,给定一个用户列表和他们之间的好友关系,
// 求出具有最多共同好友的用户对。
//
//问题函数定义:
//
//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.

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值