writerの解説にあるcolor codingという確率的algorithmは面白いので見ておくべき。 グラフに限らず、全ての要素が異なる何かをひとつ見つける場合の一般に使えそう。

## implementation

#include <iostream>
#include <vector>
#include <set>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
using namespace std;
int main() {
// input
int n, m; cin >> n >> m;
vector<int> a(m), b(m);
repeat (i,m) {
cin >> a[i] >> b[i];
-- a[i]; -- b[i];
}
// select vertices and edges
const int root = 0;
set<int> v1;
repeat (i,m) {
if (b[i] == root) v1.insert(a[i]);
if (a[i] == root) v1.insert(b[i]);
}
vector<set<int> > g1(n);
repeat (i,m) {
if (v1.count(b[i])) g1[a[i]].insert(b[i]);
if (v1.count(a[i])) g1[b[i]].insert(a[i]);
}
// find a cycle
bool ans = false;
repeat (e,m) {
int i = a[e];
int j = b[e];
if (i == root or j == root) continue;
bool g1_i_count_j = g1[i].count(j); g1[i].erase(j);
bool g1_j_count_i = g1[j].count(i); g1[j].erase(i);
if (not g1[i].empty() and not g1[j].empty()) {
if (g1[i].size() >= 2 or g1[j].size() >= 2 or g1[i] != g1[j]) {
ans = true;
}
}
if (g1_i_count_j) g1[i].insert(j);
if (g1_j_count_i) g1[j].insert(i);
if (ans) break;
}
// output
cout << (ans ? "YES" : "NO") << endl;
return 0;
}