-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path10871.go
77 lines (68 loc) · 1.39 KB
/
10871.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// UVa 10871 - Primed Subsequence
package main
import (
"fmt"
"os"
)
const max = 46340 // √(2^31-1)
var primes = sieve()
func sieve() []bool {
p := make([]bool, max+1)
p[0], p[1] = true, true
for i := 2; i*i <= max; i++ {
if !p[i] {
for j := 2 * i; j <= max; j += i {
p[j] = true
}
}
}
return p
}
func isPrime(n int) bool {
if n <= max {
return !primes[n]
}
for i := range primes {
if i*i > n {
break
}
if !primes[i] && n%i == 0 {
return false
}
}
return true
}
func solve(n int, sequence []int) (int, string) {
preSum := make([]int, n+1)
for i := 1; i <= n; i++ {
preSum[i] = preSum[i-1] + sequence[i-1]
}
for length := 2; length <= n; length++ {
for i := length; i <= n; i++ {
if isPrime(preSum[i] - preSum[i-length]) {
str := fmt.Sprint(sequence[i-length : i])
return length, str[1 : len(str)-1]
}
}
}
return 0, ""
}
func main() {
in, _ := os.Open("10871.in")
defer in.Close()
out, _ := os.Create("10871.out")
defer out.Close()
var t, n int
for fmt.Fscanf(in, "%d", &t); t > 0; t-- {
fmt.Fscanf(in, "%d", &n)
sequence := make([]int, n)
for i := range sequence {
fmt.Fscanf(in, "%d", &sequence[i])
}
if length, subSequence := solve(n, sequence); length == 0 {
fmt.Fprintln(out, "This sequence is anti-primed.")
} else {
fmt.Fprintf(out, "Shortest primed subsequence is length %d: %s\n", length, subSequence)
}
}
}