Analysis : Simulation, sorting. When the gender of this question is female, the negative sign is only a sign. If -2200 appears, it is impossible to appear at 2200. Therefore, int can also be used instead of string (if you use map to traverse, it will time out )
AC code (there is a timeout code below, using map):
#include<iostream>#include<vector>#include<string.h>#include<stdio.h>#include<queue>#include<map>#include<algorithm>
using namespace std;int n,m,k;int road[10001][10001];int gend[10001];
map<int,vector<int>>ma;struct Node{
int a,b;};
vector<Node>ans;intcmp(Node x,Node y){
if(x.a != y.a)return x.a<y.a;return x.b<y.b;}intmain(){
scanf("%d%d",&n,&m);fill(gend,gend+10001,9);for(int i =0;i<m;i++){
string a,b;
cin>>a>>b;if(a[0]=='-')
gend[abs(stoi(a))]=0;else
gend[abs(stoi(a))]=1;if(b[0]=='-')
gend[abs(stoi(b))]=0;else
gend[abs(stoi(b))]=1;int x =abs(stoi(a));int y =abs(stoi(b));
road[x][y]= road[y][x]=1;
ma[x].push_back(y);
ma[y].push_back(x);}scanf("%d",&k);for(int i =0;i<k;i++){
int a,b;scanf("%d%d",&a,&b);
a =abs(a);
b =abs(b);int num =0;
ans.clear();for(int j =0;j<ma[a].size();j++){
for(int p =0;p<ma[b].size();p++){
if(ma[a][j]== b || ma[b][p]== a)continue;int mm = ma[a][j];int ll = ma[b][p];if(gend[mm]== gend[a]&& gend[ll]== gend[b]&& road[mm][ll]==1){
num ++;
Node temp ;
temp.a = mm;
temp.b = ll;
ans.push_back(temp);}}}printf("%d\n",num);sort(ans.begin(),ans.end(),cmp);for(int i =0;i<ans.size();i++)printf("%04d %04d\n",ans[i].a,ans[i].b);}return0;}
Timeout code
#include<iostream>#include<algorithm>#include<math.h>#include<cstring>#include<queue>#include<stack>#include<map>
using namespace std;int n,m,k;
map<string,vector<string>>frd;
map<string,map<string,int>>ma;
map<string,int>gender;struct node{
int a,b;};intcmp(node x,node y){
if(x.a != y.a)return x.a < y.a;return x.b<y.b;}intmain(){
cin>>n>>m;for(int i =0; i < m ;i++){
string a,b;
cin>>a>>b;if(a[0]=='-')gender[a]=1;else gender[a]=0;if(b[0]=='-')gender[b]=1;else gender[b]=0;
ma[a][b]=1;
ma[b][a]=1;
frd[a].push_back(b);
frd[b].push_back(a);}
cin>>n;for(int i =0; i < n ;i++){
string a,b;cin>>a>>b;int cnt =0;
node ans[100001];for(int i =0; i < frd[a].size();i++){
for(int j =0; j <frd[b].size();j++){
if(ma[frd[a][i]][frd[b][j]]==1&& gender[frd[a][i]]== gender[a]&& gender[frd[b][j]]== gender[b]&& frd[a][i]!= b && frd[b][j]!= a){
ans[cnt].a =abs(stoi(frd[a][i]));
ans[cnt].b =abs(stoi(frd[b][j]));
cnt++;}}}
cout<<cnt<<endl;sort(ans,ans+cnt,cmp);for(int i =0; i < cnt; i++)printf("%04d %04d\n",ans[i].a,ans[i].b);}return0;}