Skip to content

Commit cab852b

Browse files
committed
CF402D
1 parent db428c5 commit cab852b

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

main/400-499/402D.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
. "fmt"
6+
"io"
7+
"math/bits"
8+
)
9+
10+
// github.com/EndlessCheng/codeforces-go
11+
func CF402D(_r io.Reader, out io.Writer) {
12+
in := bufio.NewReader(_r)
13+
gcd := func(a, b int) int {
14+
for a != 0 {
15+
a, b = b%a, a
16+
}
17+
return b
18+
}
19+
20+
var n, m, v, g, ans int
21+
Fscan(in, &n, &m)
22+
a := make([]int, n)
23+
gs := make([]int, n)
24+
for i := range a {
25+
Fscan(in, &a[i])
26+
g = gcd(g, a[i])
27+
gs[i] = g
28+
}
29+
bad := make(map[int]bool, m)
30+
for ; m > 0; m-- {
31+
Fscan(in, &v)
32+
bad[v] = true
33+
}
34+
35+
f := func(x int) (res int) {
36+
k := bits.TrailingZeros(uint(x))
37+
if bad[2] {
38+
res -= k
39+
} else {
40+
res += k
41+
}
42+
x >>= k
43+
for i := 3; i*i <= x; i += 2 {
44+
for x%i == 0 {
45+
x /= i
46+
if bad[i] {
47+
res--
48+
} else {
49+
res++
50+
}
51+
}
52+
}
53+
if x > 1 {
54+
if bad[x] {
55+
res--
56+
} else {
57+
res++
58+
}
59+
}
60+
return
61+
}
62+
for _, v := range a {
63+
ans += f(v)
64+
}
65+
g = 1
66+
for i := n - 1; i >= 0; i-- {
67+
if res := f(gs[i] / g); res < 0 {
68+
ans -= (i + 1) * res
69+
g = gs[i]
70+
}
71+
}
72+
Fprint(out, ans)
73+
}
74+
75+
//func main() { CF402D(os.Stdin, os.Stdout) }

main/400-499/402D_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import (
4+
"github.com/EndlessCheng/codeforces-go/main/testutil"
5+
"testing"
6+
)
7+
8+
// https://codeforces.com/problemset/problem/402/D
9+
// https://codeforces.com/problemset/status/402/problem/D
10+
func TestCF402D(t *testing.T) {
11+
// just copy from website
12+
rawText := `
13+
inputCopy
14+
5 2
15+
4 20 34 10 10
16+
2 5
17+
outputCopy
18+
-2
19+
inputCopy
20+
4 5
21+
2 4 8 16
22+
3 5 7 11 17
23+
outputCopy
24+
10`
25+
testutil.AssertEqualCase(t, rawText, 0, CF402D)
26+
}

0 commit comments

Comments
 (0)