Advertisement
SorahISA

F. 質數家族 (primeconn) -Subtask 1+2

Oct 20th, 2022
1,295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<vector<int>> adj;
  5. vector<int> vis;
  6.  
  7. void dfs(int now, int limit) {
  8.     vis[now] = 1;
  9.     for (int x : adj[now]) {
  10.         if (!vis[x] and x <= limit) dfs(x, limit);
  11.     }
  12. }
  13.  
  14. bool isprime(int x) {
  15.     for (int i = 2; i*i <= x; ++i) {
  16.         if (x % i == 0) return false;
  17.     }
  18.     return x != 1;
  19. }
  20.  
  21. bool canconn(int p, int q) { /// p < q
  22.     int len_p = 1, len_q = 1;
  23.    
  24.     if (p >=   10) ++len_p;
  25.     if (p >=  100) ++len_p;
  26.     if (p >= 1000) ++len_p;
  27.     if (q >=   10) ++len_q;
  28.     if (q >=  100) ++len_q;
  29.     if (q >= 1000) ++len_q;
  30.    
  31.     if (len_q == len_p) {
  32.         int diff = 0;
  33.         while (p or q) {
  34.             if (p % 10 != q % 10) ++diff;
  35.             p /= 10, q /= 10;
  36.         }
  37.         return diff == 1;
  38.     }
  39.    
  40.     if (len_q == len_p + 1) {
  41.         if (len_q == 4) return p == q % 1000;
  42.         if (len_q == 3) return p == q % 100;
  43.         if (len_q == 2) return p == q % 10;
  44.     }
  45.    
  46.     return false;
  47. }
  48.  
  49. int main() {
  50.     ios_base::sync_with_stdio(0), cin.tie(0);
  51.    
  52.     int N; cin >> N;
  53.    
  54.     adj.resize(N+5);
  55.     vis.resize(N+5);
  56.    
  57.     vector<int> primes;
  58.     for (int i = 1; i <= N; ++i) {
  59.         if (isprime(i)) primes.emplace_back(i);
  60.     }
  61.    
  62.     for (int p : primes) for (int q : primes) {
  63.         if (p < q and canconn(p, q)) {
  64.             adj[p].emplace_back(q);
  65.             adj[q].emplace_back(p);
  66.         }
  67.     }
  68.    
  69.     int ans = 0;
  70.     for (int p : primes) {
  71.         fill(begin(vis), end(vis), 0);
  72.         dfs(2, p);
  73.         if (!vis[p]) ans += p;
  74.     }
  75.     cout << ans << "\n";
  76.    
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement