Sample Input:
10 18
-2001 1001
-2002 -2001
1004 1001
-2004 -2001
-2003 1005
1005 -2001
1001 -2003
1002 1001
1002 -2004
-2004 1001
1003 -2002
-2003 1003
1004 -2002
-2001 -2003
1001 1003
1003 -2001
1002 -2001
-2002 -2003
5
1001 -2001
-2003 1001
1005 -2001
-2002 -2004
1111 -2003
Sample Output:
4
1002 2004
1003 2002
1003 2003
1004 2002
4
2001 1002
2001 1003
2002 1003
2002 1004
0
1
2003 2001
0
题解:
用unordered_map<int,bool>
表示a
,b
是否是朋友,用vector<int> v[i]
表示i
的同性朋友
先找a
的同性朋友c
,再找b
的同性朋友d
,若c
、d
是朋友,就将c
、d
加入结果数组,
最后对结果数组进行排序
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
using namespace std;
unordered_map<int,bool> arr;
vector<int> v[10001];
vector<pair<int,int>> ans;
int n,m,k;
bool cmp(pair<int,int> a,pair<int,int> b){
return a.first != b.first ? a.first < b.first : a.second < b.second;
}
int main(){
cin >> n >> m;
for(int i=0;i<m;i++){
string a,b;
cin >> a >> b;
if(a.length() == b.length()){
v[abs(stoi(a))].push_back(abs(stoi(b)));
v[abs(stoi(b))].push_back(abs(stoi(a)));
}
arr[abs(stoi(a))*10000 + abs(stoi(b)) ] = arr[abs(stoi(b))*10000 + abs(stoi(a))] = true;
}
cin >> k;
while(k--){
string a,b;
cin >> a >> b;
ans.clear();
for(int i=0;i<v[abs(stoi(a))].size();i++){
for(int j=0;j<v[abs(stoi(b))].size();j++){
int a_friend = v[abs(stoi(a))][i];
int b_friend = v[abs(stoi(b))][j];
if(a_friend == abs(stoi(b)) || b_friend == abs(stoi(a))) continue;
if(arr[a_friend*10000 + b_friend] == true){
ans.push_back(make_pair(a_friend,b_friend));
}
}
}
sort(ans.begin(),ans.end(),cmp);
cout << ans.size() << endl;
for(int i=0;i<ans.size();i++){
printf("%04d %04d\n",ans[i].first,ans[i].second);
}
}
system("pause");
return 0;
}