PAT1139 First Contact(模拟)

题意:

A和B告白,必须通过A的同性朋友和B的同性朋友传达,要求输出所以可能的两个朋友的情况

思路:

这题有些复杂,我一开始想复杂了,上来就用dfs+回溯做,结果超时,其实只要遍历所有A的朋友和B的朋友,看这两者是否互为朋友即可。不过这题还有很多地方要注意,我还是看别人的代码写的。

https://www.liuchuo.net/archives/4210

#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<unordered_map>
#include<set>
using namespace std;
const int maxn = 10050;
const int inf = 10000;
unordered_map<int, bool> arr;
vector<int> v[maxn];
struct node {
	int a, b;
};

bool cmp(node x, node y) {
	if (x.a != y.a) {
		return x.a < y.a;
	} else {
		return x.b < y.b;
	}
}

int main() {
	int n, m, k;
	scanf("%d%d", &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))* inf + abs(stoi(b))] = arr[abs(stoi(b))* inf+ abs(stoi(a))] = true;
	}
	scanf("%d", &k);
	for (int i = 0; i < k; i++) {
		int c, d;
		cin >> c >> d;
		vector<node> ans;
		for (int j = 0; j < v[abs(c)].size(); j++) {
			for (int l = 0; l < v[abs(d)].size(); l++) {
				int s = v[abs(c)][j];
				int e = v[abs(d)][l];
				if (s == abs(d) || e == abs(c))
					continue;
				if (arr[s*inf + e] == true) {
					ans.push_back(node{ s,e });
				}
			}
		}
		sort(ans.begin(), ans.end(), cmp);
		printf("%d\n", ans.size());
		for (int j = 0; j < ans.size(); j++) {
			printf("%04d %04d\n", ans[j].a, ans[j].b);
		}
	}
	return 0;
}

 

转载于:https://www.cnblogs.com/seasonal/p/10343605.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值