First Contact (30)

本文介绍了一种解决特定社交匹配问题的算法实现,该问题来源于PAT竞赛的一个挑战。通过使用C++编程语言,作者详细解释了如何根据人物性别及其朋友圈进行有效匹配的过程,并附上了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://www.patest.cn/contests/pat-a-101-149-3-2017-12-09/D


本题不难,难点在于建模,其他难点就在于条件判断比较多

直接上代码


#include <cstdio>
#include <vector>
#include <string>
#include <string.h>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

struct Person{
    string id;
    int sex;
    vector<string> friends;
    Person(){}
};

typedef pair<string,string> Result;
map<string , Person> persons;
string from , to;
vector<Result> results;
bool cmp(const Result &a , const Result &b){
    if(a.first!=b.first)return a.first<b.first;
    else return a.second<b.second;
}

void _search( string person_c  ){
    for(string person_d : persons[person_c].friends){
        if( (persons[from].sex==persons[to].sex && persons[person_c].sex ==persons[person_d].sex) ||
             (persons[from].sex!=persons[to].sex && persons[person_c].sex !=persons[person_d].sex) ) {
            for(string person_to : persons[person_d].friends){
                if(person_to==to && persons[person_to].sex==persons[person_d].sex)
                    results.push_back(make_pair( person_c , person_d ));
            }
        }
    }
}

int main(){
    freopen("C:\\Users\\yehao\\Desktop\\Test\\bin\\Release\\in1.txt", "r", stdin);
    int n , m;
    cin>>n>>m;
    string a , b;
    for(int i=0;i<m;i++){
        cin>>a>>b;
        int sa=(a[0]=='-')?-1:1;
        int sb=(b[0]=='-')?-1:1;
        if(sa==-1)a.erase(a.begin());
        if(sb==-1)b.erase(b.begin());
        persons[a].id=a;
        persons[b].id=b;
        persons[a].sex=sa;
        persons[b].sex=sb;
        persons[a].friends.push_back(b);
        persons[b].friends.push_back(a);
    }

    /*
    for(auto it=persons.begin() ; it!=persons.end() ; ++it){
        cout<<it->second.id<<"-----";
        for(auto s:it->second.friends)cout<<s<<"  ";
        cout<<endl;
    }*/

    int k;
    cin>>k;
    for(int i=0;i<k;i++){
        cin>>from>>to;
        if(from[0]=='-')from.erase(from.begin());
        if(to[0]=='-')to.erase(to.begin());
        results.clear();
        for(string c : persons[from].friends) if(persons[c].sex == persons[from].sex ) _search(c);
        sort(results.begin() , results.end() , cmp);
        printf("%d\n",results.size());
        for(auto &p : results)printf("%s %s\n",p.first.c_str() , p.second.c_str() );
    }

    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值