题意:
A,C是同性,,,B,D 是异性 ,,
现在A看上了B,要给B写信,但是不能直接给B,
然后找到了同性的朋友C,让C给C的朋友D,
再由D转交给B,,这时候D也得是B的朋友
给定A和B,问这样的C,D有多少,并输出
思路:
朋友关系用邻接表储存,
每个人的同性别的朋友用vector存起来
然后每次分别遍历A,B的同性别朋友c,d,,,然后判断c,d是不是朋友关系,是的话就符合C,D,存起来
注意:若遍历A的同性朋友的时候,找到了B要跳过,因为他们不行直接相互传递
#include<bits/stdc++.h>
#include<cstring>
#define FI first
#define SE second
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int maxn = 300 + 77;
int n, m, q, id = 1;
map<string, int> mp;
string u, v;
vector<string> vec[maxn];
bool d[maxn][maxn];
bool cmp(P a, P b) {
return (a.FI == b.FI ? a.SE < b.SE : a.FI < b.FI);
}
vector<P> ans;
void solve() {
ans.clear();
cin >> u >> v;
int t1 = mp[u], t2 = mp[v];
if(!t1 || !t2) {
cout << 0 << endl;
return;
}
string x, y;
for(auto i : vec[t1]) {
int t3 = mp[i];
if(t3 == t2) continue;
if(i[0] == '-') x = i.substr(1, 4);
else x = i.substr(0, 4);
for(auto j : vec[t2]) {
int t4 = mp[j];
if(t4 == t1) continue;
if(d[t3][t4]) {
if(j[0] == '-') y = j.substr(1, 4);
else y = j.substr(0, 4);
ans.push_back(P(x, y));
}
}
}
cout << ans.size() << endl;
sort(ans.begin(), ans.end(), cmp);
for(auto k : ans) {
cout << k.FI << " " << k.SE << endl;
}
return;
}
int main() {
cin >> n >> m;
for(int i = 1; i <= m; ++i) {
cin >> u >> v;
if(!mp[u]) mp[u] = id++; int t1 = mp[u];
if(!mp[v]) mp[v] = id++; int t2 = mp[v];
if(u.size() == v.size()) {
vec[t1].push_back(v);
vec[t2].push_back(u);
}
d[t1][t2] = d[t2][t1] = 1;
}
cin >> q;
for(int i = 1; i <= q; ++i) {
solve();
}
return 0;
}