题意:
- 给一个长度为 n 的数组 a ,数组中两两不互质的数可以建一条边,即$gcd(a[i],a[j]) ≠ 1$,i,j之间存在伊奥无向边
- 问 s 到 t 的最短路径是多长,并输出
题解
- 根据唯一分解定理,所有的数都可以表示为$\prod p_i^{k_j}$
- 1e9之内所有的数,其不同质数数量不会很多(本体数据3e5,更少了,不会超过10个)
- 所以我们可以利用这些质数来建边
#include<bits/stdc++.h> #define debug1(a) cout<<#a<<'='<< a << endl; #define debug2(a,b) cout<<#a<<" = "<<a<<" "<<#b<<" = "<<b<<endl; #define debug3(a,b,c) cout<<#a<<" = "<<a<<" "<<#b<<" = "<<b<<" "<<#c<<" = "<<c<<endl; #define debug4(a,b,c,d) cout<<#a<<" = "<<a<<" "<<#b<<" = "<<b<<" "<<#c<<" = "<<c<<" "<<#d<<" = "<<d<<endl; #define debug5(a,b,c,d,e) cout<<#a<<" = "<<a<<" "<<#b<<" = "<<b<<" "<<#c<<" = "<<c<<" "<<#d<<" = "<<d<<" "<<#e<<" = "<<e<<endl; #define endl "\n" #define fi first #define se second //#define int long long using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> PII; typedef pair<LL,LL> PLL; //#pragma GCC optimize(3,"Ofast","inline") //#pragma GCC optimize(2) const int N = 3e5+10; int a[N]; int n,s,t; //int primes[N], cnt; bool st[N]; vector<vector<int>> pr(N+1),edge(2*N+1); int dist[2*N]; int pre[2*N]; void get_primes(int n) { for (int i = 2; i <= n; i ++ ) { if (st[i]) continue; // primes[cnt ++ ] = i; for (int j = i; j <= n; j += i){ st[j] = true; pr[j].push_back(i); } } } void solve() { memset(dist,0x3f,sizeof dist); cin >> n; for(int i = 1;i <= n;i ++)cin >> a[i]; cin >> s >> t; get_primes(N-1); for(int i = 1;i <= n;i ++) { for(auto x:pr[a[i]]) { //debug2(i,x+n); edge[i].push_back(x + n); edge[x + n].push_back(i); } } dist[s] = 0; queue<int> q;q.push(s); while(q.size()) { int y = q.front();q.pop(); for(auto x:edge[y]) { //debug2(y,x); if(dist[x] > dist[y] + 1) { dist[x] = dist[y] + 1; pre[x] = y; q.push(x); } } } if(dist[t] == 0x3f3f3f3f) { cout << -1 << endl; return ; } stack<int> sta;sta.push(t); while(t != s) { t = pre[t]; if(t <= n)sta.push(t); } cout << sta.size() << endl; while(sta.size()) { cout << sta.top() << " "; sta.pop(); } } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T = 1;//cin >> T; while(T--){ //puts(solve()?"YES":"NO"); solve(); } return 0; } /* */
标签:pre,dist,int,质数,while,bfs,建图,primes From: https://www.cnblogs.com/cfddfc/p/17048190.html