题目链接: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;
}