Skip to content

Commit b15d3a5

Browse files
committed
Solved problem 265D from codeforces
1 parent c4684b9 commit b15d3a5

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
Idea:
3+
- Dynamic programming with Prime factorization.
4+
- Any two numbers share at least one prime factor, then the GCD between them
5+
not equal to 1.
6+
- Based on the previous point we can start a DP from each index and try
7+
to add a new number to the sequence based on the prime factorization of the
8+
current number.
9+
*/
10+
11+
#include <bits/stdc++.h>
12+
13+
using namespace std;
14+
15+
int const N = 1e5 + 1;
16+
int n, a[N], dp[N];
17+
vector<vector<int> > g, d;
18+
19+
int rec(int idx) {
20+
if(idx == n)
21+
return 0;
22+
23+
int &ret = dp[idx];
24+
if(ret != -1)
25+
return ret;
26+
ret = 0;
27+
28+
for(int i = 0, cur; i < d[idx].size(); ++i) {
29+
cur = upper_bound(g[d[idx][i]].begin(), g[d[idx][i]].end(), idx) - g[d[idx][i]].begin();
30+
if(cur != g[d[idx][i]].size())
31+
ret = max(ret, rec(g[d[idx][i]][cur]) + 1);
32+
}
33+
34+
return ret;
35+
}
36+
37+
int main() {
38+
g.resize(N);
39+
d.resize(N);
40+
41+
scanf("%d", &n);
42+
for(int i = 0; i < n; ++i) {
43+
scanf("%d", a + i);
44+
45+
int x = a[i], sqrtx = sqrt(x);
46+
for(int j = 2, fr; j <= sqrtx; ++j) {
47+
fr = 0;
48+
while(x % j == 0)
49+
++fr, x /= j;
50+
if(fr != 0)
51+
g[j].push_back(i), d[i].push_back(j);
52+
}
53+
if(x != 1)
54+
g[x].push_back(i), d[i].push_back(x);
55+
}
56+
57+
memset(dp, -1, sizeof dp);
58+
int res = 0;
59+
for(int i = 0; i < n; ++i)
60+
res = max(res, rec(i) + 1);
61+
printf("%d\n", res);
62+
63+
return 0;
64+
}

CodeForces/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@
9797
- [262A. Roma and Lucky Numbers](http://codeforces.com/problemset/problem/262/A)
9898
- [263A. Beautiful Matrix](http://codeforces.com/problemset/problem/263/A)
9999
- [263D. Cycle in Graph](http://codeforces.com/contest/263/problem/D)
100+
- [265D. Good Sequences](http://codeforces.com/contest/265/problem/D)
100101
- [266A. Stones on the Table](http://codeforces.com/problemset/problem/266/A)
101102
- [266B. Queue at the School](http://codeforces.com/problemset/problem/266/B)
102103
- [268A. Games](http://codeforces.com/problemset/problem/268/A)

0 commit comments

Comments
 (0)