[Internet interview] questions about the circle of friends

Source: Internet
Author: User

Problem description:

If we know that there are n people and m friends (stored in the number R ). If two people are friends directly or indirectly (friends of friends ...),

They think they belong to the same circle of friends,

Write a program to find the total number of friends in the N groups.

Suppose n = 5, M = 3,
R = {1, 2}, {2, 3}, {4, 5} indicates five people, 1 and 2 are friends, and 2 and 3 are friends, 4 and 5 are friends,

Then 1, 2, 3 belong to one circle of friends, 4, 5 belong to another circle of friends, and the result is two circle of friends.

Finally, analyze the time and space complexity of the Code. The score will refer to the Code correctness and efficiency.

It is said that the query set is used to solve the problem .... I don't understand the code ......

 

// Circle of friends # include <iostream> using namespace STD; int set [10001]; // The Inline int find (int x) Search Algorithm with Path Optimization) {int I, j, R; r = x; while (set [R]! = R) {r = set [R];} I = x; while (I! = R) {J = set [I]; set [I] = r; I = J;} return r ;} // optimize and query the inline void merge (int x, int y) {int T = find (x); int H = find (y ); if (T 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.