第二题题意(略有超时):
找出两个数,这两个数满足所有给出的数字对中至少有一个数是这两个数中的其中之一。
思路:
假设存在,那么第一对数字对中至少有一个是最终所求的两个数字之一,如果存在另外的一个数字对,与第一对数字对完全不同,那么存在的两个数字必然是这两对数字对的四种自由组合之一;如果不存在完全不同的另外一个数字对,那么第一对就是所求。所以
- 找到与第一对数字(a,b)对完全不同的另外一对数字对(c,d),如果没有找到,就对所有的数字对检查第一对中的两个数字是不是满足条件;
- 找到了就对所有的数字对检查(a,c)、(a,d)、(b,c)、(b,d)是否满足条件;
代码如下:
#include<iostream>
using namespace std;
int inputArray[300000][2];
bool check(int n, int a, int b){
for(int i = 0; i < n; i++){
if(a == inputArray[i][0] || a == inputArray[i][1] || b == inputArray[i][0] || b == inputArray[i][1]){
} else{
return false;
}
}
return true;
}
int main(){
int n, m, index = 0;
while(cin >> n >> m){
if(n < 2 || m < 1) return 0;
for(int i = 0; i < m; i++){
cin >> inputArray[i][0] >> inputArray[i][1];
}
int temA = inputArray[0][0];
int temB = inputArray[0][1];
//找到一个与第一个完全不相同的输入对
for(int i = 1; i < m; i++){
if(temA != inputArray[i][0] && temA != inputArray[i][1] && temB != inputArray[i][0] && temB != inputArray[i][1]){
index = i;
break;
}
}
//如果没有找到,那么存在的话就是第一对
if(index == 0){
if(check(m, inputArray[0][0], inputArray[0][1])){
cout << "YES" << endl;
break;
}
}
//找到了就检查两个对的四种组合情况
if(check(m, inputArray[0][0], inputArray[index][0])){
cout << "YES" << endl;
break;
}
if(check(m, inputArray[0][0], inputArray[index][1])){
cout << "YES" << endl;
break;
}
if(check(m, inputArray[0][1], inputArray[index][0])){
cout << "YES" << endl;
break;
}
if(check(m, inputArray[0][1], inputArray[index][1])){
cout << "YES" << endl;
break;
}
cout << "NO" << endl;
}
}