I don’t want to say more about this question…
Note that the ID can be -0000!! So we should store ID in a string instead of int valid.
I have no time to simply my code,so I’m sorry that it would be a little tedious.
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <map>
#include <string.h>
#include<stack>
#include <unordered_map>
#include <queue>
using namespace std;
const int MAXN = 330;
int G[MAXN][MAXN];
map<string, int> Index;
queue<string> A;
queue<string> B;
int N, M, K;
void solve(string u,string v)
{
int cnt = 0;
string uu, vv;
if (u.size() == 4) uu = u;
else uu = u.substr(1, 4);
if (v.size() == 4) vv = v;
else vv = v.substr(1, 4);
int ui = Index[uu], vi = Index[vv];
if (u.size()==v.size()) { //uv同性
for (auto a : Index)
{
if (a.first != vv && G[ui][a.second] == 1) {//a是u的同性朋友
for (auto b : Index)
{
if (G[a.second][b.second] == 1&&b.first!=uu)//b是a的同性朋友
{
if (G[b.second][vi] == 1) {
++cnt;
A.push(a.first);
B.push(b.first);
}
}
}
}
}
cout << cnt << endl;
while (!A.empty())
{
cout << A.front() << " " << B.front() << endl;
A.pop(); B.pop();
}
}
else {
for (auto a : Index)
{
if (a.first != vv && G[ui][a.second] == 1) {//a是u的同性朋友
for (auto b : Index)
{
if (b.first != vv && G[a.second][b.second] == 2)//b是a的异性朋友
{
if (G[b.second][vi] == 1) {
++cnt;
A.push(a.first);
B.push(b.first);
}
}
}
}
}
cout << cnt << endl;
while (!A.empty())
{
cout << A.front() << " " << B.front() << endl;
A.pop(); B.pop();
}
}
}
int main() {
memset(G, 0, sizeof(G));
cin >> N >> M;
string u, v,uu,vv;
int ui, vi;
for (int i = 0; i < M; i++)
{
cin >> u >> v;
if (u.size() == 4) {
uu = u;
}else {
uu = u.substr(1, 4);
}
if (v.size() == 4) {
vv = v;
}
else {
vv = v.substr(1, 4);
}
if (Index.count(uu)) ui = Index[uu];
else
{
ui = Index.size();
Index[uu] = ui;
}
if (Index.count(vv)) vi = Index[vv];
else {
vi = Index.size();
Index[vv] = vi;
}
if (u.size()==v.size()) {
G[ui][vi] = 1;
G[vi][ui] = 1;
}
else {
G[ui][vi] = 2;
G[vi][ui] = 2;
}
}
cin >> K;
while (K--)
{
cin >> u >> v;
if (u.size() == 4) uu = u;
else uu = u.substr(1, 4);
if (v.size() == 4) vv = v;
else vv = v.substr(1, 4);
if (!Index.count(uu) || !Index.count(vv)) {
cout << 0 << endl;
continue;
}
solve(u, v);
}
return 0;
}