1139 First Contact (30 分)
题目:大意是说,a想和b交流,但是又不好意思,a拖朋友c,c又找了d,d最后才把消息准达到了b。
因为提到了love这个词,我心想:典型的a,b,恋爱,外加基友c和闺蜜d的日常。
读完题目后,人有傻了,ab两个还能是同性!同性还墨迹个屁啊。
好,言归正传,说题目。
如果a,b同性,c,d也要是相同性别,如果ab异性,那么c和a同性,d和b同性
这里有一个问题,怎么样判定ab异性,用int型接受,然后用if(a*b<0)是不行的,因为无论是+0000还是-0000,被int接受后,都失去了性别辨识度。所以我就用笨方法,用字符串接受aa,bb.看aa[0]和bb【0】的符号位了。然后再转成int型
string aa,bb;
cin>>aa>>bb;
int a=stoi(aa,0,10);int b=stoi(bb,0,10);
if(aa[0]=='-'&&bb[0]=='-'||aa[0]!='-'&&bb[0]!='-'){//同性
xxxx
}else{
xxxx
}
接着在说一下解题思考,用map<int ,friends>来记录每个人的朋友,很现实化,friends是一个类,又分同性朋友,异性朋友。一开始一个朋友都没有,然后来一个朋友记录一个。
例如same【5555】=1,意思是我有一个同性朋友5555;
class friends{
public:
int same[10001]={0};
int differ[10001]={0};
};
接着就上完整代码吧:对于每一组要牵线说话的ab,先判断x性别,再用两组for训话去找,因为用了map和数组记录,因此时间复杂度很低。代码虽然长了一点,但是好理解。
//
// Created by 江左 on 2021/2/7.
//
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <math.h>
using namespace std;
class friends{
public:
int same[10001]={0};
int differ[10001]={0};
};
int main() {
map<int,friends> peoples;
int m,n;cin>>m>>n;
for (int i = 0; i < n; ++i) {
string aa,bb;
cin>>aa>>bb;int a=stoi(aa,0,10);int b=stoi(bb,0,10);
if(aa[0]=='-'&&bb[0]=='-'||aa[0]!='-'&&bb[0]!='-'){
peoples[abs(a)].same[abs(b)]=1;
peoples[abs(b)].same[abs(a)]=1;
}else{
peoples[abs(a)].differ[abs(b)]=1;
peoples[abs(b)].differ[abs(a)]=1;
}
}
int t;cin>>t;
for (int i = 0; i < t; ++i) {
string aa,bb;
cin>>aa>>bb;
int a=stoi(aa,0,10);int b=stoi(bb,0,10),c,d;
vector<int> result;
if(aa[0]=='-'&&bb[0]=='-'||aa[0]!='-'&&bb[0]!='-'){//同性
map<int,friends>::iterator it;
for (it=peoples.begin();it!=peoples.end();it++) {//找一个a同性好朋友c
if(peoples[abs(a)].same[it->first]==1&&it->first!=abs(a)&&it->first!=abs(b)){//c不能是b
c=it->first;
}else continue;
map<int,friends>::iterator iter;
for (iter=peoples.begin();iter!=peoples.end();iter++) {//找一个c同性好朋友d
if(peoples[abs(c)].same[iter->first]==1&&iter->first!=abs(a)&&iter->first!=abs(b)){//d不能是a.不能是b
d=iter->first;//d是c的同性好朋友
if(peoples[d].same[abs(b)]==1){//d和b是同性好朋友
result.push_back(c);
result.push_back(d);
}
}
}
}
}else{//异性
map<int,friends>::iterator it;
for (it=peoples.begin();it!=peoples.end();it++) {
if(peoples[abs(a)].same[it->first]==1&&it->first!=abs(a)&&it->first!=abs(b)){
c=it->first;//c是a的同性好朋友
}else continue;
map<int,friends>::iterator iter;
for (iter=peoples.begin();iter!=peoples.end();iter++) {
if (peoples[abs(c)].differ[iter->first] == 1 &&iter->first!=abs(a)&&iter->first!=abs(b)) {
d=iter->first;//d是c的异性好朋友
if(peoples[d].same[abs(b)]){//d和b是同性好朋友
result.push_back(c);
result.push_back(d);
}
}
}
}
}
printf("%d\n",result.size()/2);
for (int j = 0; j < result.size(); j+=2) {
printf("%04d %04d\n",result[j],result[j+1]);
}
}
return 0;
}