Advertisement
Zuneve

w

Mar 27th, 2024
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
  5. using ll = long long;
  6. const int INF = 1e9 + 7;
  7.  
  8. double rng() { return double(rand()) / RAND_MAX; }
  9.  
  10. int n, m;
  11. vector<set<int>> gr;
  12. vector<int> color;
  13.  
  14. int dfs(int u) {
  15.     int cnt = 0;
  16.     for (int v : gr[u]) {
  17.         if (color[u] == color[v]) cnt++;
  18.     }
  19.     return cnt;
  20. }
  21.  
  22. signed main() {
  23.     cin >> n >> m;
  24.     gr.resize(n);
  25.     for (int i = 0; i < m; i++) {
  26.         int a, b;
  27.         cin >> a >> b;
  28.         --a;
  29.         --b;
  30.         gr[a].insert(b);
  31.         gr[b].insert(a);
  32.     }
  33.     color.resize(n);
  34.     for (int i = 0; i < n; i++) {
  35.         color[i] = rnd() % 3;
  36.     }
  37.     int start = clock();
  38.     long double t = 1.0;
  39.     int f_old = 0;
  40.     for (int i = 0; i < n; i++) {
  41.         f_old += dfs(i);
  42.     }
  43.     while (clock() - start <= 1.9 * CLOCKS_PER_SEC && f_old > 0) {
  44.         if (t <= 0.00001) {
  45.             for (int i = 0; i < n; i++) {
  46.                 color[i] = rnd() % 3;
  47.             }
  48.             f_old = 0;
  49.             for (int i = 0; i < n; i++) {
  50.                 f_old += dfs(i);
  51.             }
  52.             if (!f_old) break;
  53.             t = 1.0;
  54.         }
  55.         int i = rnd() % n;
  56.         int prev_color = color[i];
  57.         int flip_color = rnd() % 3;
  58.         while (flip_color == prev_color) {
  59.             flip_color = rnd() % 3;
  60.         }
  61.         int cnt = f_old;
  62.         cnt -= dfs(i);
  63.         color[i] = flip_color;
  64.         cnt += dfs(i);
  65.         if (cnt < f_old || rng() < exp(((double) f_old - cnt) / t)) {
  66.             f_old = cnt;
  67.         } else {
  68.             color[i] = prev_color;
  69.         }
  70.         t *= 0.99;
  71.     }
  72.     for (int i : color) {
  73.         cout << i + 1 << ' ';
  74.     }
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement