火星是一种不同寻常的蜘蛛的家园——二元蜘蛛。现在,火星科学家们正在观察一群n只蜘蛛,其中第1只有一条腿。有些蜘蛛彼此是朋友。也就是说,第i个蜘蛛和第j个蜘蛛是朋友,如果gcd(ai, aj) 1,即存在某个整数k > 2,使得a;和一个;同时除以k,没有余数。这里gcd(z, y)表示整数x和y的最大公约数(gcd)。科学家们发现蜘蛛可以传递信息。如果两只蜘蛛是朋友,那么它们可以在一秒钟内直接传递信息。否则,蜘蛛必须将消息传递给他的朋友,他又必须将消息传递给他的朋友,依此类推,直到消息到达接收者。让我们看一个例子。假设一只有八条腿的蜘蛛想要向一只有15条腿的蜘蛛发送一条信息。他不能直接做,因为gcd(8,15) 1。但他可以通过有六条腿的蜘蛛发送信息,因为gcd(8,6) 2和gcd(6,15)3。因此,消息将在两秒钟内到达。现在,科学家们正在观察第s只蜘蛛是如何向第t只蜘蛛发送信息的。研究人员有一个假设,蜘蛛总是以最佳方式传递信息。出于这个原因,科学家们需要一个程序来计算发送信息的最短时间,并推断出最佳路线之一。
输入和第一行输入包含一个整数n (2 <n <3.105)——群落中的蜘蛛数量。第二行输入包含n个整数a1, a2,, an (1 < a < 3- 105)——蜘蛛的腿的数量。第三行输入包含两个整数s和t (1 s,t n)—消息必须在它们之间发送的蜘蛛。输出如果不可能在给定的蜘蛛对之间传输消息,则输出-1。否则,在输出的第一行打印整数t (t 2 1)-参与消息传输的spider的数量(即以秒加1为单位的消息传递的最小时间)。在第二行,打印t个不同的整数b1, b2,…, bt (1 < bi S n)——按照从发送方到接收方的顺序,消息应该遵循的spider的id。如果消息有几个最佳路由,则输出其中任何一个。
Examples
input
Copy
7 2 14 9 6 8 15 11 5 6
output
Copy
3 5 4 6
input
Copy
7 2 14 9 6 8 15 11 5 7
output
Copy
-1
input
Copy
7 2 14 9 6 8 15 11 5 5
output
Copy
1 5
题解:
每个点与他gcd不为1的点连边会有很多边,但是如果我们把每个点与他的质因数(每个点质因数的数量是很少的)连接,就会少很多边,
然后最短路,找最短距离即可
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<cstdio>
using namespace std;
//#define int long long
const int N = 2e6 + 10;
typedef pair<int, int> PII;
typedef long long ll;
int n,m;
int h[N],e[N],ne[N],idx;
void add(int l,int r)
{
e[idx] = r;
ne[idx] = h[l];
h[l] = idx ++;
}
int st[N];
int ans[N];
int dis[N];
vector<int> f[N];
void solve()
{
int n;
scanf("%d",&n);
for(int i = 0;i <= n + 500000;i++)
{
h[i] = -1;
dis[i] = 1e9;
}
for(int i = 1;i <= n;i++)
{
int x;
scanf("%d",&x);
for(int j = 2;j <= x/j;j++)
{
if(x % j == 0)
{
while(x%j == 0)
{
x /= j;
}
f[i].push_back(j+n);
f[j+n].push_back(i);
// add(i,j + n);
// add(j + n,i);
}
}
if(x > 1)
{
f[i].push_back(x+n);
f[x+n].push_back(i);
// add(i,x + n);
// add(x + n,i);
}
}
queue<int> q;
int s,t;
scanf("%d%d",&s,&t);
q.push(s);
dis[s] = 0;
while(q.size())
{
int now = q.front();
q.pop();
for(auto j : f[now])
{
if(dis[j] > dis[now] + 1)
{
dis[j] = dis[now] + 1;
ans[j] = now;
q.push(j);
}
}
}
if(dis[t] == 1e9)
{
printf("-1");
return ;
}
vector<int> p;
int x = t;
while(x)
{
if(x <= n)
p.push_back(x);
x = ans[x];
}
printf("%d\n",p.size());
reverse(p.begin(),p.end());
for(auto i:p)
printf("%d ",i);
}
//1 2 4
signed main()
{
// ios::sync_with_stdio(0);
// cin.tie(0);cout.tie(0);
int t = 1;
// cin >> t;
//scanf("%d",&t);
while (t--)
{
solve();
}
return 0;
}
//1 1 1 0 1
//1 1 1 0 1
//1 1 1 0 1
//1 1 1 0 1
//0 1 1 1 1
//0 1 1 1 1