Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.9 kB
0
Indexable
Never
#include<iostream>
#include<unordered_map>
#include<unordered_set>
#include<string>

class FriendsGraph {
private:
    std::unordered_map<std::string, std::unordered_set<std::string>> adjacencyList;

public:
    void addFriend(const std::string& name) {
        if (adjacencyList.find(name) == adjacencyList.end()) {
            // Add a new friend to the graph
            adjacencyList[name] = std::unordered_set<std::string>();
            std::cout << "Friend added: " << name << std::endl;
        } else {
            std::cout << "Friend already exists: " << name << std::endl;
        }
    }

    void makeFriendship(const std::string& friend1, const std::string& friend2) {
        if (adjacencyList.find(friend1) != adjacencyList.end() && adjacencyList.find(friend2) != adjacencyList.end()) {
            // Add an edge between friends
            adjacencyList[friend1].insert(friend2);
            adjacencyList[friend2].insert(friend1);
            std::cout << "Friendship established between " << friend1 << " and " << friend2 << std::endl;
        } else {
            std::cout << "Invalid friend names. Please ensure both friends exist." << std::endl;
        }
    }

    void displayFriends() {
        std::cout << "Friends Graph:" << std::endl;
        for (const auto& entry : adjacencyList) {
            std::cout << entry.first << " has friends: ";
            for (const auto& friendName : entry.second) {
                std::cout << friendName << " ";
            }
            std::cout << std::endl;
        }
    }
};

int main() {
    FriendsGraph friendsGraph;
    int choice;

    do {
        std::cout << "\nFriends Graph Management\n";
        std::cout << "1. Add Friend\n";
        std::cout << "2. Make Friendship\n";
        std::cout << "3. Display Friends\n";
        std::cout << "0. Exit\n";
        std::cout << "Enter your choice: ";
        std::cin >> choice;

        switch (choice) {
            case 1: {
                std::string newFriend;
                std::cout << "Enter the friend's name: ";
                std::cin >> newFriend;
                friendsGraph.addFriend(newFriend);
                break;
            }
            case 2: {
                std::string friend1, friend2;
                std::cout << "Enter the names of two friends to make them friends: ";
                std::cin >> friend1 >> friend2;
                friendsGraph.makeFriendship(friend1, friend2);
                break;
            }
            case 3:
                friendsGraph.displayFriends();
                break;
            case 0:
                std::cout << "Exiting the program.\n";
                break;
            default:
                std::cout << "Invalid choice. Please try again.\n";
        }
    } while (choice != 0);

    return 0;


}
Leave a Comment