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;
}

 

posted @ 2018-07-22 22:57  seasonal  阅读(174)  评论(0编辑  收藏  举报