link: http://codeforces.com/contest/330/problem/E
1 /* 2 ID: zypz4571 3 LANG: C++ 4 TASK: 192e.cpp 5 */ 6 7 #include <iostream> 8 #include <cstdio> 9 #include <cstdlib> 10 #include <cstring> 11 #include <cmath> 12 #include <cctype> 13 #include <algorithm> 14 #include <queue> 15 #include <deque> 16 #include <queue> 17 #include <list> 18 #include <map> 19 #include <set> 20 #include <vector> 21 #include <utility> 22 #include <functional> 23 #include <fstream> 24 #include <iomanip> 25 #include <sstream> 26 #include <numeric> 27 #include <cassert> 28 #include <ctime> 29 #include <iterator> 30 const int INF = 0x3f3f3f3f; 31 const int dir[8][2] = {{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}}; 32 using namespace std; 33 map<pair<int,int>,bool> coll; 34 int a[100009]; 35 int main ( int argc, char *argv[] ) 36 { 37 #ifndef ONLINE_JUDGE 38 //freopen("in.txt", "r", stdin); 39 #endif 40 int n, m; cin>>n>>m; 41 double d=clock(); srand(time(0)); 42 for (int i = 0, x, y; i < m; ++i) { 43 cin>>x>>y; 44 coll.insert(make_pair(make_pair(x,y),true)); 45 coll.insert(make_pair(make_pair(y,x),true)); 46 } 47 for (int i = 0; i < n; ++i) a[i] = i+1; 48 bool t; 49 while ((clock()-d)/CLOCKS_PER_SEC < 2.9) { 50 random_shuffle(a, a+n); 51 a[n] = a[0]; t = false; 52 for (int i = 0; i < m; ++i) 53 if (coll[make_pair(a[i],a[i+1])]) { 54 t = true; break; 55 } 56 if (!t) break; 57 } 58 if (t) printf("-1\n"); 59 else for (int i = 0; i < m; ++i) printf("%d %d\n", a[i], a[i+1]); 60 return EXIT_SUCCESS; 61 } /* ---------- end of function main ---------- */
note the use of random_shuffle.
the possibility of each try of success is about (1-2/n)^n which is big enough when n is very large so we can use this nondeterminisitic solution.