Created
January 31, 2017 10:36
-
-
Save cAstraea/f615edc12cc7518b9e0951b697ad4eb3 to your computer and use it in GitHub Desktop.
javascript solution, Finds the minimum number of moves required to rearrange the tanks so that each row and each column contains a single tank, and one such shortest sequence of moves
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
process.stdin.resume(); | |
process.stdin.setEncoding('ascii'); | |
let input_stdin = ''; | |
let input_stdin_array = ''; | |
let input_currentline = 0; | |
process.stdin.on('data', (data) => { | |
input_stdin += data; | |
}); | |
process.stdin.on('end', () => { | |
input_stdin_array = input_stdin.split('\n'); | |
main(); | |
}); | |
function readLine() { | |
return input_stdin_array[input_currentline++]; | |
} | |
// ///////////// ignore above this line //////////////////// | |
const resultArray = []; | |
const pairR = { | |
int: 0, | |
char: '' | |
}; | |
const pairC = { | |
int: 0, | |
char: '' | |
}; | |
const index = []; | |
function deployRooks(roworcolumn, numberofRooks, X, Y) { | |
for (let i = 0; i < numberofRooks; ++i) { | |
index[i] = i; | |
} | |
// sort | |
for (let i = 0; i < numberofRooks; ++i) { | |
for (let j = i + 1; j < numberofRooks; ++j) { | |
if (roworcolumn[j] < roworcolumn[i]) { | |
const tmp = roworcolumn[j]; | |
roworcolumn[j] = roworcolumn[i]; | |
roworcolumn[i] = tmp; | |
const tmpIndex = index[j]; | |
index[j] = index[i]; | |
index[i] = tmpIndex; | |
} | |
} | |
} | |
// move up / left | |
for (let i = 0; i < numberofRooks; ++i) { | |
for (; roworcolumn[i] > i; --roworcolumn[i]) { | |
pairR.int = index[i] + 1; | |
pairR.char = X; | |
resultArray.push(pairR); | |
} | |
} | |
//move down / right | |
for (let i2 = numberofRooks - 1; i2 >= 0; --i2) { | |
for (; roworcolumn[i2] < i2; ++roworcolumn[i2]) { | |
pairC.int = index[i2] + 1; | |
pairC.char = Y; | |
resultArray.push(pairC); | |
} | |
} | |
} | |
function main() { | |
// write your code here. | |
// call `readLine()` to read a line. | |
// use console.log() to write to stdout | |
const a = parseInt(readLine(), 10); | |
const rows = []; | |
const columns = []; | |
for (let i = 0; i < a; ++i) { | |
const c = readLine().split(' '); | |
rows.push(c[0]); | |
columns.push(c[1]); | |
--rows[i]; | |
--columns[i]; | |
} | |
deployRooks(rows, a, 'Up', 'Down'); // deploys rows | |
deployRooks(columns, a, 'Left', 'Right'); // deploy on columns | |
//console.log(resultArray); | |
console.log(resultArray.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment