编程介的小学生 2019-05-29 19:54 采纳率: 0.4%
浏览 145

人员分组以后如何计算人数的问题,怎么采用 C 程序的代码编写的过程的方式加以实现的

Problem Description
One day dandelion and her friends decides to play outside. As there are so many people , they decide to divide into several parts . Dandelion wants to know how many friends will be together with her. The way they use to divide is : everyone can choose one people to join in her group, Such as if A chooses B to join in her group , then B will leave the group she is in now , and joins in the group that A is in . One can also choose some people who has already in her group. All of dandelion抯 friends are expressed as an integer 2,3... n and dandelion is expressed as 1.The choosing work begins from dandelion then the friend who are signed as 2 ?until the friend who are signed as n .

Input
Each case begins with an integer n, (0<n<=1000000) stands for the number of people.
Then follows n lines , the i+1 line contains an integer p, stands for people who are signed as i chooses the one who are signed as p to join in her group.

Output
The output contains one line for each data set : the number of friends will be together with dandelion at last .

Sample Input
3
3
3
1
3
2
1
2

Sample Output
2
0

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-09 22:50
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    这是一个典型的图论问题,我们可以使用邻接矩阵来表示这个图。在C++中,我们可以创建一个二维数组,其中每个元素代表图中的一个节点,并且值为1或0,表示是否被选择。

    以下是一个简单的实现:

    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
        
        int graph[1005][1005];
        // 初始化邻接矩阵
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= n; j++) {
                graph[i][j] = 0;
            }
        }
    
        while(cin >> n) {
            int a, b;
            cin >> a >> b;
            
            graph[a-1][b-1] = 1;
            graph[b-1][a-1] = 1;
        }
    
        int res = 0;
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= n; j++) {
                if(graph[i][j]) {
                    res++;
                }
            }
        }
        cout << res << endl;
        return 0;
    }
    

    在这个程序中,我们首先读取n个数据点,然后遍历每一个数据点,将它们加入到邻接矩阵中。最后,我们遍历所有的节点,并检查它们是否已经加入了某个节点,如果是,则我们将res加一。

    这只是一个基本的实现,你可以根据你的需求进行修改和优化。例如,你可能想要添加一些错误处理,或者使用更高效的算法来找出答案。

    评论

报告相同问题?