巨坑。
注意点:
- 用负号表示女生,而不是负数表示女生,区别在一个特殊样例“-0000”
- 输出需用4位整数,不足4位用0补齐
#include<cstdio>
#include<vector>
#include<algorithm>
#include<iostream>
#include<string>
#define maxn 100000
using namespace std;
vector<int> g[maxn]; // graph
int gender[maxn] = {0};
struct friendsType {
int f, s; // first one and second one
};
int setgender(string str) {
int a;
sscanf(str.c_str(), "%d", &a);
if (str[0] == '-') {
a = -a;
gender[a] = -1;
}
else gender[a] = 1;
return a;
}
int delete_gender(int a) {
if (a < 0) return -a;
else return a;
}
bool compare(friendsType a, friendsType b) {
if (a.f != b.f) {
return a.f < b.f;
}
else return a.s < b.s;
}
vector<friendsType> findfirend(int a, int b) {
vector<friendsType> fl; // friend list
int fa, fb;
for (int i = 0; i < g[a].size(); i++) {
fa = g[a][i];
if (fa == b) continue;
if (gender[fa] != gender[a]) continue;
for (int j = 0; j < g[b].size(); j++) {
fb = g[b][j];
if (fb == a) continue;
if (gender[fb] != gender[b]) continue;
vector<int>::iterator it;
for (it = g[fa].begin(); it != g[fa].end(); it++) {
if (*it == fb) break;
}
if (it != g[fa].end()) {
friendsType ftemp;
ftemp.f = fa;
ftemp.s = fb;
fl.push_back(ftemp);
}
}
}
return fl;
}
int main () {
int N, M, K;
scanf("%d %d", &N, &M);
int a, b;
string stra, strb;
while(M--) {
cin >> stra >> strb;
a = setgender(stra);
b = setgender(strb);
g[a].push_back(b);
g[b].push_back(a);
}
scanf("%d", &K);
while(K--) {
scanf("%d %d", &a, &b);
a = delete_gender(a);
b = delete_gender(b);
vector<friendsType> fl = findfirend(a, b);
printf("%d\n", fl.size());
sort(fl.begin(), fl.end(), compare);
for (int i = 0; i < fl.size(); i++) {
printf("%04d %04d\n", fl[i].f, fl[i].s);
}
}
return 0;
}