-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path1139_First Contact (30).cpp
71 lines (64 loc) · 2.13 KB
/
1139_First Contact (30).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
// 分别维护每个人的男女朋友关系
// 1. 对于A,B时候,其C,D的朋友中应该分别把B,A给排除掉
class Human {
public:
int gender;
unordered_set<string> maleFriends;
unordered_set<string> femaleFriends;
void addFriend(string id) {
if (id[0] == '-')
femaleFriends.insert(id);
else
maleFriends.insert(id);
}
bool isFriend(string id) {
return femaleFriends.find(id) != femaleFriends.end() || maleFriends.find(id) != maleFriends.end();
}
};
unordered_set<string> findFriends(const Human &human, bool sameGender=true) {
if ((!human.gender && sameGender) || (human.gender && !sameGender))
return human.femaleFriends;
else
return human.maleFriends;
}
int toID(string s) {
int r = 0;
for (int i = (s[0] == '-' ? 1 : 0); i < s.size(); i++)
r = r*10 + s[i]-'0';
return r;
}
int main() {
int n, m, k;
string p, q;
unordered_map<string, Human> humans;
cin >> n >> m;
for (int i = 0 ;i < m; i++) {
cin >> p >> q;
humans[p].gender = p[0] == '-' ? 0 : 1;
humans[p].addFriend(q);
humans[q].gender = q[0] == '-' ? 0 : 1;
humans[q].addFriend(p);
}
cin >> k;
for (int i = 0; i < k; i++) {
cin >> p >> q;
vector<pair<int, int>> ans;
if (humans.find(p) != humans.end() && humans.find(q) != humans.end() && p != q) {
auto pFriends = findFriends(humans[p]);
auto qFriends = findFriends(humans[q]);
bool sameGender = humans[p].gender == humans[q].gender;
for (auto &pID : pFriends) {
for (auto &qID : qFriends) {
if (pID != qID && pID != q && qID != p && humans[pID].isFriend(qID))
ans.push_back(make_pair(toID(pID), toID(qID)));
}
}
sort(ans.begin(), ans.end());
}
cout << ans.size() << endl;
for (auto &it : ans) cout << setfill('0') << setw(4) << it.first << " " << setfill('0') << setw(4) << it.second << endl;
}
return 0;
}