2020美团笔试题目:送餐小区数量

2020美团笔试题目:送餐小区数量

题目:现在有n个订单,为了帮助送餐小哥增加送餐量,可以让送餐小哥将同一个小区的订单同时送过去,但是现在只有订单之间的关系,要通过订单之间的关系找找到有多少个小区,将同一个小区的订单id进行输出。
输入:第一行两个整数n,m表示有n个订单,m个订单之间的关系,后面m行表示两个订单是同一个小区的

5 3
2 1
4 3
5 2

输出

2
1 2 5
3 4

有两个小区,以及每个小区的订单id
解法:参考之前的找老乡的方法,对每一对输入建立父子关系,直到找到祖先结点停止。

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <stack>
#include <map>

using namespace std;

int main(){
    int n,m;
    cin>>n>>m;
    vector<int> connect(n,0);
    for(int i=0;i<n;i++){		 // 结点关系初始化
        connect[i] = -i;
    }
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        if(a<b){
            if(connect[b-1] < 0)
                connect[b-1] = a - 1;	// 大订单的父节点是小订单
            else
                connect[a-1] = connect[b-1];	// 大订单已经有父节点,让小订单指向有父节点的大订单
        }
        if(a>b){
            if(connect[a-1] < 0)
                connect[a-1] = b - 1;
            else
                connect[b-1] = connect[a-1];
        }

    }
    int count = 0;
    map<int,set<int>> nodeNum;  // 祖先结点,和祖先一个小区的结点
    for(int i=0;i<n;i++){
        int j = i;
        set<int> temp{j};      // 存放从当前结点到最终祖先结点的所有中间结点
        while(j != -connect[j]){  // 还有父结点的话继续查找
            temp.insert(j);
            j = connect[j];      // 更新遍历结点
        }
        if(nodeNum.find(j) != nodeNum.end()){
            nodeNum[j].insert(temp.begin(),temp.end());
        } else
            nodeNum[j] = temp;
    }
    cout<<nodeNum.size()<<endl;
    for(auto i : nodeNum){
        for(auto j:i.second){
            cout<<j+1<<' ';
        }
        cout<<endl;
    }
    return 0;
}

输出测试:
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值