[C++] PAT 1139 First Contact (30分)

该博客介绍了PAT编程竞赛中1139题First Contact的解题思路,提供了样例输入和输出,并展示了如何找出两个角色的同性朋友并排序结果。
摘要由CSDN通过智能技术生成

在这里插入图片描述

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> 表示ab是否是朋友,用vector<int> v[i]表示i的同性朋友
先找a的同性朋友c,再找b的同性朋友d,若cd是朋友,就将cd加入结果数组,
最后对结果数组进行排序

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值