Caisa is now at home and his son has a simple task for him.
Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer qqueries. Each query is one of the following:
- Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk(u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1.
- Format of the query is "2 v w". You must change the value of vertex v to w.
You are given all the queries, help Caisa to solve the problem.
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.
Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.
Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
For each query of the first type output the result of the query.
4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4
-1
1
2
-1
1
gcd(x, y) is greatest common divisor of two integers x and y.
题目大意:
给出一个总节点数量为n的树,每个节点有权值,进行q次操作,每次操作有两种选项:
1. 询问节点v到root之间的路径上的各个节点,求满足条件 gcd(val[i], val[v]) > 1 的 距离v最近的节点的下标。
2. 将节点v的值求改为w。
解法:
时间限制为10s,给的好宽松,直接暴力dfs过。
代码:
#include <cstdio>
#include <vector>
#define N_max 123456
using namespace std;
int n, m, ans;
int val[N_max], fa[N_max];
vector <int> G[N_max];
int gcd(int a, int b) {
return b ? gcd(b, a%b) : a;
}
void build(int v, int fav) {
fa[v] = fav;
for (int i = 0; i < G[v].size(); i++)
if (G[v][i] != fav) {
fa[G[v][i]] = v;
build(G[v][i], v);
}
}
void addedge(int x, int y) {
G[x].push_back(y);
}
void init() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &val[i]);
for (int i = 1; i <= n-1; i++) {
int x, y;
scanf("%d%d", &x, &y);
addedge(x, y);
addedge(y, x);
}
build(1, 0);
}
int query(int v) {
int w=val[v];
v = fa[v];
while (v) {
if (gcd(val[v], w) > 1)
return v;
v = fa[v];
}
return -1;
}
void solve() {
for (int i = 1; i <= m; i++) {
int tmp, v, w;
scanf("%d", &tmp);
if (tmp == 1) {
scanf("%d", &v);
printf("%d\n", query(v));
}
else {
scanf("%d%d", &v, &w);
val[v] = w;
}
}
}
int main() {
init();
solve();
}