Pairs

Toad Ivan has m pairs of integers, each integer is between 1 and n, inclusive. The pairs are (a1,b1),(a2,b2),…,(am,bm).

He asks you to check if there exist two integers x and y (1≤x<y≤n) such that in each given pair at least one integer is equal to x or y.

Input
The first line contains two space-separated integers n and m (2≤n≤300000, 1≤m≤300000) — the upper bound on the values of integers in the pairs, and the number of given pairs.

The next m lines contain two integers each, the i-th of them contains two space-separated integers ai and bi (1≤ai,bi≤n,ai≠bi) — the integers in the i-th pair.

Output
Output “YES” if there exist two integers x and y (1≤x<y≤n) such that in each given pair at least one integer is equal to x or y. Otherwise, print “NO”. You can print each letter in any case (upper or lower).

Examples
input

4 6
1 2
1 3
1 4
2 3
2 4
3 4

output

NO

题目大意:给m对数,每个数字都在1~n的范围内,求解是否存在一对数,使得每组输入的数据中至少有一个在这对数中,如果存在,输出YES,否则输出NO。

思路:
既然每组数至少有一个存在与正确答案中,如果最终结果是YES,那么在第一对数里面至少有一个数字在正确答案中。可以遍历第一对数的两个数字,然后枚举给定的m组数,如果某一组数的两个值都没有出现,让这两个数的标记位++,记录不满足条件的个数的变量 sum 也 ++。
如果一共有 t 组不满足条件,恰好有一个数字不满足条件的次数为 t ,也就是说可以用 t 和刚刚遍历的数字来组成一组,一定可以满足条件。
因为遍历用的数字不能满足条件的有 sum 组,而这 sum 组被 t 恰好补充。

#include<bits/stdc++.h>
using namespace std;
struct p {
	int a, b;
	p() {

	}
	p(int a, int b) {
		this->a = a;
		this->b = b;
	}
};
int n, m, a, b;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	int v[n + 10];
	vector<p> arr;
	for (int i = 0; i < m; i++) {
		cin >> a >> b;
		arr.emplace_back(p(a, b));
	}
	vector<int> d = { arr[0].a,arr[0].b };
	for (int i : d) {
		memset(v, 0, sizeof v);
		int sum = 0;
		for (auto j : arr) {
			if (j.a != i && j.b != i) {
				sum++;
				v[j.a]++;
				v[j.b]++;
			}
		}
		int ma = *max_element(v + 1, v + n + 1);
		if (ma == sum) {
			cout << "YES" << endl;
			return 0;
		}
	}
	cout << "NO" << endl;
	return 0;
}
posted @ 2019-05-29 07:17  correct  阅读(194)  评论(0)    收藏  举报