-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206-concealed-square.js
More file actions
96 lines (74 loc) · 2.06 KB
/
206-concealed-square.js
File metadata and controls
96 lines (74 loc) · 2.06 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Concealed Square
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
function processData(input) {
const tokens = input.trim().split(/\s+/);
if (!tokens.length) return;
const n = parseInt(tokens[0]);
const constraints = new Int8Array(2 * n).fill(-1);
for (let i = 1; i <= n; i++) {
const val = parseInt(tokens[i]);
const pos = (n - i) * 2;
constraints[pos] = val;
}
const digits = new Int8Array(n);
let found = false;
function dfs(k, carry) {
if (found) return;
if (k === n) {
let currentCarry = carry;
let valid = true;
for (let pos = n; pos < 2 * n - 1; pos++) {
let sum = currentCarry;
const startI = Math.max(0, pos - (n - 1));
const endI = Math.min(n - 1, pos);
for (let i = startI; i <= endI; i++) {
sum += digits[i] * digits[pos - i];
}
const digit = sum % 10;
currentCarry = Math.floor(sum / 10);
if (constraints[pos] !== -1 && constraints[pos] !== digit) {
valid = false;
break;
}
}
if (valid && currentCarry === 0) {
let res = "";
for (let i = n - 1; i >= 0; i--) res += digits[i];
console.log(res);
found = true;
}
return;
}
let partialSum = carry;
for (let i = 1; i < k; i++) {
partialSum += digits[i] * digits[k - i];
}
let startD = k === n - 1 ? 1 : 0;
let endD = k === n - 1 ? 3 : 9;
for (let d = startD; d <= endD; d++) {
let currentSum = partialSum;
if (k === 0) currentSum += d * d;
else currentSum += 2 * digits[0] * d;
const calculatedDigit = currentSum % 10;
if (constraints[k] !== -1 && calculatedDigit !== constraints[k]) {
continue;
}
digits[k] = d;
dfs(k + 1, Math.floor(currentSum / 10));
if (found) return;
}
}
dfs(0, 0);
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});