ZOOM笔试股票推荐,带树重量的查并集,输入输出写的很菜

#include <iostream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

template<class T>
class UF{
private:
    int m_cnt;
    unordered_map<T,T> parent;
    unordered_map<T,int> size;
public:
    UF(){};
    void connect(T p,T q)
    {
        T rootp=find(p);
        T rootq=find(q);
        if(rootp==rootq) return;
        parent[rootq]=rootp;
        size[rootp]+=size[rootq];
        --m_cnt;
    }
    void insert(T key){
        if(parent.count(key)) return;
        parent[key]=key;
        size[key]=1;
        ++m_cnt;
    }
    T find(T x){
        //找到根节点
        if(x!=parent[x]){
            parent[x]= find(parent[x]);
        }
        return parent[x];
    }
    bool connected(T p,T q){
        T rootp=find(p);
        T rootq=find(q);
        return rootp==rootq;
    }
    int count(){
        return m_cnt;
    }
    int getSize(T q){
        T rootq= find(q);
        return size[rootq];
    }
};

unordered_map<string,unordered_set<string>> people2com;
UF<string> uf;
void insertPeople(string s1,string s2){
    stringstream ss1(s1);
    stringstream coms(s2);
    vector<string> person;
    vector<string> companys;
    string tmp;
    while(ss1>>tmp) person.push_back(tmp);
    string p=person[1];
    while(coms>>tmp){
        //保存这个人关注的公司
        people2com[p].insert(tmp);
        uf.insert(tmp);
    }
    auto it=people2com[p].begin();
    string root=*it;
    ++it;
    while(it!=people2com[p].end()){
        //跟第一个公司相连接
        uf.connect(root,*it);    
        ++it;
    }
}
int getCnt(string s1){
    int ret=0;
    stringstream ss1(s1);
    string tmp;
    vector<string> person;
    while(ss1>>tmp) person.push_back(tmp);
    string p=person[1];
    if(people2com.count(p)){
        int size=people2com[p].size();
        ret=uf.getSize(*people2com[p].begin());
        ret-=size;
    }else{
        ret=-1;
    }
    return ret;
}
int main(){
    string n;
    getline(cin,n);
    for(int i=0;i< stoi(n);++i){
        string work;
        getline(cin,work);
        if(work[0]=='1'){
            string companys;
            getline(cin,companys);
            insertPeople(work,companys);
        }else{
            int ret=getCnt(work);
            if(ret<0) cout<<"error"<<endl;
            else cout<<ret<<endl;
        }
    }

}

#Zoom#
全部评论

相关推荐

06-23 18:25
沈阳大学 Java
HR已读不回,是我说话方式不对吗?
大白之主:你是串子吗? hr: 我们不招人了,把岗位挂着boss只是因为我闲得慌
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 15:07
点赞 评论 收藏
分享
有担当的灰太狼又在摸鱼:零帧起手查看图片
点赞 评论 收藏
分享
AAA专业长城贴瓷砖刘大爷:这样的简历我会直接丢进垃圾桶,花里胡哨的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-23 18:34
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务