- 输出要以4位数字形式,别忘了%04d;
- 存在id为0,若录入图时以int型录入数据,无法判断0000和-0000,因此使用char数组录入;
- 若查询A和B,则得出结果中,id1!=B, id2!=A。
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <iostream>
using namespace std;
vector<int> G[100010];
int N,M;
int gender[100010];
struct fri
{
int id1,id2;
}p[100010];
bool cmp(fri a,fri b)
{
if(a.id1!=b.id1)return a.id1<b.id1;
else return a.id2<b.id2;
}
int change(char a[])
{
int result=0;
int index=0;
if(a[index]=='-')index++;
while(a[index]>='0'&&a[index]<='9')
{
result=10*result+a[index]-'0';
index++;
}
return result;
}
int main()
{
scanf("%d%d",&N,&M);
memset(gender,0,sizeof(gender));
for(int i=0;i<M;i++)
{
char c1[10],c2[10];
scanf("%s%s",&c1,&c2);
int temp1=change(c1);
int temp2=change(c2);
gender[temp1]=c1[0]=='-'?-1:1;
gender[temp2]=c2[0]=='-'?-1:1;
G[temp1].push_back(temp2);
G[temp2].push_back(temp1);
}
int K;
scanf("%d",&K);
for(int i=0;i<K;i++)
{
int c1,c2;
int num=0;
scanf("%d%d",&c1,&c2);
int temp1=abs(c1);
int temp2=abs(c2);
for(int j=0;j<G[temp1].size();j++)
{
int C=G[temp1][j];
if(gender[C]==gender[temp1]&&C!=temp2)
{
for(int k=0;k<G[C].size();k++)
{
int B=G[C][k];
if(find(G[B].begin(),G[B].end(),temp2)!=G[B].end())
{
if(gender[B]==gender[temp2]&&B!=temp1)
{
p[num].id1=C;
p[num].id2=B;
num++;
}
}
}
}
}
sort(p,p+num,cmp);
printf("%d\n",num);
for(int i=0;i<num;i++)
{
printf("%04d %04d\n",p[i].id1,p[i].id2);
}
}
system("pause");
return 0;
}