const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => BigInt(str))).toString())
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    let times = (a - b) / (c - d);
    if (times * (c - d) < a - b) {
        times += 1n;
    }
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        const a = BigInt(test[0]);
        const b = BigInt(test[1]);
        const c = BigInt(test[2]);
        const d = BigInt(test[3]);
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            console.log(b.toString());
            return;
        }

        totalSleepAmount = b;
        totalTime = b;

        if (c <= d) {
            console.log(-1);
            return;
        }

        const cycleSleepTime = BigInt(c - d);
        let cyclesCount = BigInt((a - totalSleepAmount) / cycleSleepTime);
        cyclesCount = cyclesCount * cycleSleepTime < a - totalSleepAmount ? cyclesCount + BigInt(1) : cyclesCount;
        totalSleepAmount += cyclesCount * cycleSleepTime;

        console.log((cyclesCount * c + b).toString());
    });
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = BigInt(test[0]);
        const b = BigInt(test[1]);
        const c = BigInt(test[2]);
        const d = BigInt(test[3]);
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount = b;
        totalTime = b;

        if (c <= d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        if (!c) {
            console.log(-1);
            return;
        }

        const cycleSleepTime = BigInt(c - d);
        let cyclesCount = BigInt((a - totalSleepAmount) / cycleSleepTime);
        cyclesCount = cyclesCount * cycleSleepTime < a - totalSleepAmount ? cyclesCount + BigInt(1) : cyclesCount;
        totalSleepAmount += cyclesCount * cycleSleepTime;

        console.log((cyclesCount * c + b).toString());
    });

    //result.forEach(r => console.log(r));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let count = 0;

rl.on('line', (data) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c, d] = data.split(' ').map(BigInt);
  let ans = b;
  let r = a - b;

  if (r <= 0n) {
    console.log(ans.toString());
    return;
  }

  if (c <= d) {
    console.log(-1);
    return;
  }

  let temp = r / (c - d);
  if (temp * (c - d) < r) {
    temp += 1n;
  }

  ans += temp * c;

  console.log(ans.toString());
  count++;
});

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const [a, b, c, d] = lines[i+1].split(' ').map(x => BigInt(x))
    if (a <= b) {
      console.log(b.toString(10))
    } else {
      if (c <=  d) {
        console.log(-1)
      } else {
        let t = a - b
        let f = c - d
        let p = (t - (t % f) ) / f
        if (t % f !== BigInt(0)) {
          p++
        }
        const add = p * c
        console.log((b + add).toString(10))
      }
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        const a = BigInt(test[0]);
        const b = BigInt(test[1]);
        const c = BigInt(test[2]);
        const d = BigInt(test[3]);
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            console.log(b.toString());
            return;
        }

        totalSleepAmount = b;
        totalTime = b;

        if (c <= d) {
            console.log(-1);
            return;
        }

        // if (!c) {
        //     console.log(-1);
        //     return;
        // }

        const cycleSleepTime = BigInt(c - d);
        let cyclesCount = BigInt((a - totalSleepAmount) / cycleSleepTime);
        cyclesCount = cyclesCount * cycleSleepTime < a - totalSleepAmount ? cyclesCount + BigInt(1) : cyclesCount;
        totalSleepAmount += cyclesCount * cycleSleepTime;

        console.log((cyclesCount * c + b).toString());
    });
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b);
            return;
        }

        totalSleepAmount = b;
        totalTime = b;

        if (c <= d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        if (!c) {
            console.log(-1);
            return;
        }

        const cycleSleepTime = c - d;
        const cyclesCount = Math.ceil((a - totalSleepAmount) / cycleSleepTime);
        totalSleepAmount += cyclesCount * cycleSleepTime;

        console.log(cyclesCount * c + b);
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount =b;
        totalTime = b;

        if (c < d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        let count = 0;
        let prevTotalSleepAmount  = 0;
        // while (totalSleepAmount < a && prevTotalSleepAmount !== totalSleepAmount) {
        //     prevTotalSleepAmount = totalSleepAmount;
        //     totalSleepAmount = totalSleepAmount + (c - d);
        //     totalTime += c;
        //     count++;
        // }
        const cyclesCount = Math.trunc((a - b) / (c - d));
        totalSleepAmount += cyclesCount * (c - d);
        if (totalSleepAmount >= a) {
            console.log(cyclesCount * c + b);
        } else {
            console.log(cyclesCount * c + c + b);
        }
        //result.push(totalTime);
        //console.log(totalTime.toString());
        return;
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = BigInt(test[0]);
        const b = BigInt(test[1]);
        const c = BigInt(test[2]);
        const d = BigInt(test[3]);
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount = BigInt(b);
        totalTime = BigInt(b);

        if (d >= c) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        let count = 0;
        while (totalSleepAmount < a && count < 1000) {
            totalSleepAmount += c - d;
            totalTime += c;
            count++;
        }
        //result.push(totalTime);
        console.log(totalTime.toString());
        return;
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount =b;
        totalTime = b;

        if (c < d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        let count = 0;
        let prevTotalSleepAmount  = 0;
        // while (totalSleepAmount < a && prevTotalSleepAmount !== totalSleepAmount) {
        //     prevTotalSleepAmount = totalSleepAmount;
        //     totalSleepAmount = totalSleepAmount + (c - d);
        //     totalTime += c;
        //     count++;
        // }
        const cyclesCount = Math.ceil((a - b) / (c - d));
        //totalSleepAmount += cyclesCount * (c - d);
        // if (totalSleepAmount >= a) {
        //     console.log(cyclesCount * c + b);
        // } else {
        //     console.log(cyclesCount * c + c + b);
        // }
        console.log(cyclesCount * c + b);
        //result.push(totalTime);
        //console.log(totalTime.toString());
        return;
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount = b;
        totalTime = b;

        if (c <= d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        if (!c) {
            console.log(-1);
            return;
        }

        const cycleSleepTime = c - d;
        const cyclesCount = Math.round((a - totalSleepAmount) / cycleSleepTime);
        totalSleepAmount += cyclesCount * (c - d);

        console.log(totalSleepAmount >= a ? cyclesCount * c + b : cyclesCount * c + c + b);
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount =b;
        totalTime = b;

        if (d >= c) {
            //result.push(-1);
            console.log(-1);
            return;
        }

        let count = 0;
        let prevTotalSleepAmount  = 0;
        // while (totalSleepAmount < a && prevTotalSleepAmount !== totalSleepAmount) {
        //     prevTotalSleepAmount = totalSleepAmount;
        //     totalSleepAmount = totalSleepAmount + (c - d);
        //     totalTime += c;
        //     count++;
        // }
        const cyclesCount = Math.floor((a - totalSleepAmount) / (c - d));
        totalSleepAmount += cyclesCount * (c - d);
        if (totalSleepAmount >= a) {
            console.log(cyclesCount * c + b);
        } else {
            console.log(cyclesCount * c + c + b);
        }
        //result.push(totalTime);
        //console.log(totalTime.toString());
        return;
    });

    //result.forEach(r => console.log(r));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function main() {
    // console.log("typeof inputString", typeof inputString)
    //console.log("inputString", inputString)

    const tests = inputString.slice(1).map(testStr => testStr.split(" ").map(Number));
    let result = [];
    tests.forEach(test => {
        //const [_, __, c, d] = test;
        const a = test[0];
        const b = test[1];
        const c = test[2];
        const d = test[3];
        let totalSleepAmount;
        let totalTime;

        if (b >= a) {
            //result.push(b);
            console.log(b.toString());
            return;
        }

        totalSleepAmount =b;
        totalTime = b;

        if (c < d) {
            //result.push(-1);
            console.log(-1);
            return;
        }

         if (!c) {
            console.log(-1);
        }

        let count = 0;
        let prevTotalSleepAmount  = 0;
        // while (totalSleepAmount < a && prevTotalSleepAmount !== totalSleepAmount) {
        //     prevTotalSleepAmount = totalSleepAmount;
        //     totalSleepAmount = totalSleepAmount + (c - d);
        //     totalTime += c;
        //     count++;
        // }
        const cyclesCount = Math.ceil((a - b) / (c - d));
        //totalSleepAmount += cyclesCount * (c - d);
        // if (totalSleepAmount >= a) {
        //     console.log(cyclesCount * c + b);
        // } else {
        //     console.log(cyclesCount * c + c + b);
        // }
        console.log(cyclesCount * c + b);

        //result.push(totalTime);
        //console.log(totalTime.toString());
        return;
    });

    //result.forEach(r => console.log(r));
}

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a,b,c,d]) {
    if (c < d) {
        return -1
    }
    const times = Math.ceil((a - b) / (c - d));
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    console.log(input)
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a,b,c,d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => BigInt(str))).toString().slice(0, -1))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    let times = (a - b) / (c - d);
    if (times * c < a - b) {
        times += 1n;
    }
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => BigInt(str))).toString().slice(0, -1))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    let times = (a - b) / (c - d);
    if (times * (c - d) < a - b) {
        times += 1n;
    }
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a,b,c,d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    console.log(input)
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return BigInt(b + times * c);
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return String(BigInt(b) + BigInt(times * c));
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return Number(BigInt(b) + BigInt(times * c));
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i < Number(q[0]) + 1; i++) {
        console.log(solve(q[i].split(' ').map(str => Number(str))))
    }
}
function solve([a, b, c, d]) {
    if ((a > b) && (c <= d)) {
        return -1
    }
    if (a <= b) {
        return b
    }
    const times = Math.ceil((a - b) / (c - d));
    return b + times * c;
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let count = 0;

rl.on('line', (data) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c, d] = data.split(' ').map(Number);
  let ans = b;
  let r = a - b;

  if (r <= 0) {
    console.log(ans);
    return;
  }

  if (c <= d) {
    console.log(-1);
    return;
  }

  ans += Math.ceil(r / (c - d)) * c;

  console.log(ans);
  count++;
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let count = 0;

rl.on('line', (data) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c, d] = data.split(' ').map(BigInt);
  let ans = b;
  let r = a - b;

  if (r <= 0n) {
    console.log(ans.toString());
    return;
  }

  if (c <= d) {
    console.log(-1);
    return;
  }

  let temp = r / (c - d);
  if (temp < r) {
    temp += 1n;
  }

  ans += temp * c;

  console.log(ans.toString());
  count++;
});


function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], k = data[1],
		s = trim(readline()),
		ribbon = new Array(n);
	for (var i = 0; i < n; ++i) {
		ribbon[i] = s.charCodeAt(i)-65;
	}
	var newRibbon = new Array(n);
	newRibbon[0] = s.charAt(0);
	if (k != 2) {
		var cost = 0;
		for (var i = 1; i <= n-2; ++i) {
			var a = ribbon[i-1], b = ribbon[i], c = ribbon[i+1];
			if (b == a) {
				for (b = 0; b < k; ++b) {
					if (b != a && b != c) {
						ribbon[i] = b;
						break;
					}
				}
				++cost;
			}
			newRibbon[i] = String.fromCharCode(65+ribbon[i]);
		}
		if (n != 1 && ribbon[n-1] == ribbon[n-2]) {
			for (var b = 0; b < k; ++b) {
				if (b != ribbon[n-2]) {
					ribbon[n-1] = b;
					break;
				}
			}
			++cost;
		}
		newRibbon[n-1] = String.fromCharCode(65+ribbon[n-1]);
		print(cost);
		print(newRibbon.join('').toUpperCase());
		return;
	} else {
		var dp = new Array(n);
		dp[0] = new Array(2);
		for (var c = 0; c < 2; ++c) {
			dp[0][c] = (ribbon[0] == c ? 0 : 1);
		}
		for (var i = 1; i < n; ++i) {
			dp[i] = [n, n];
			for (var c = 0; c < 2; ++c) {
				dp[i][c] = Math.min(dp[i][c], (ribbon[i] == c ? 0 : 1) +
						dp[i-1][c == 0 ? 1 : 0]);
			}
		}
		var best = dp[n-1][0], c = 0;
		if (dp[n-1][1] < best) {
			best = dp[n-1][1];
			c = 1;
		}
		for (var i = n-1; i >= 0; --i) {
			newRibbon[i] = String.fromCharCode(65+c);
			c = (c == 0 ? 1 : 0);
		}
		print(best);
		print(newRibbon.join(''));
	}
}

main();

var nk = readline().split(' ').map(Number);
var n = nk[0];
var k = nk[1];
var s = readline();
if (k == 2){
	var count1 = 0;
	var count2 = 0;
	if (n%2 == 0) {
		var s1 = 'AB'.repeat(n/2);
		var s2 = 'BA'.repeat(n/2);
	} else {
		var s1 = 'AB'.repeat(n/2) + 'A';
		var s2 = 'BA'.repeat(n/2) + 'B';
	}
	for (var i=0; i<n; i++) {
		if (s[i] != s1[i]) count1++;
		else count2++;
	}
	if (count2>count1){
		print(count1);
		print(s1);
	} else {
		print(count2);
		print(s2);
	}
} else {
	s = s.split('');
	var count = 0;
	for (var i=0; i<n-1; i++) {
	if (s[i] == s[i+1]) {
	count++;
	if (i == n-2){
			if (s[i] == 'A') s[i+1] = 'B';
			else s[i+1] = 'A';
		} else {
			if (s[i] != 'A' && s[i+2] != 'A') s[i+1] = 'A';
			if (s[i] != 'B' && s[i+2] != 'B') s[i+1] = 'B';
			if (s[i] != 'C' && s[i+2] != 'C') s[i+1] = 'C';
		}
	}
}
print(count);
print(s.join(''));
}


var input = readline().split(' ').map(Number), n = input[0];
var str = readline();

var counter = 0;
for (var i = 1; i < str.length; i++) {
    if (str[i] != str[i-1]) counter++;
}
write(Math.min(counter + 3, n));

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()

function main() {
  const n = getInt()
  const s = getLine()[0]

  let lastZero = 0
  let lastOne = 0
  const L = []
  const R = []

  for (let i = 0; i < n; ++i) {
    if (s[i] === '0') {
      lastZero = lastOne + 1
      L[i] = lastZero
    } else {
      lastOne = lastZero + 1
      L[i] = lastOne
    }
  }

  lastZero = lastOne = 0
  for (let i = n - 1; i >= 0; --i) {
    if (s[i] === '0') {
      lastZero = lastOne + 1
      R[i] = lastZero
    } else {
      lastOne = lastZero + 1
      R[i] = lastOne
    }
  }

  let ans = 0
  let i = 0
  while (i < n) {
    let j = i + 1
    const a = i
    while (j < n && s[j - 1] !== s[j]) {
      j ++
    }

    const b = j - 1
    const cur = b - a + 1

    const best = calc(a, b, s, L, R)
    ans = Math.max(ans, cur + best)
    i = j
  }
  print(ans)
}

function calc(a, b, s, L, R) {
  const n = s.length
  let one = (a - 1 >= 0 ? L[a - 1] - (s[a] === s[a - 1] ? 1 : 0): 0)
  one += (b + 1 < n ? R[b + 1] - (s[b] === s[b + 1] ? 1 : 0): 0)

  const left =  (s[a] === '0' ? '1' : '0')
  const right = (s[b] === '0' ? '1' : '0')

  let two = (a - 1 >= 0 ? L[a - 1] - (left === s[a - 1] ? 1 : 0): 0)
  two += (b + 1 < n ? R[b + 1] - (right === s[b + 1] ? 1 : 0): 0)

  return Math.max(one, two)
}

var x = readline();
var n = readline();
var ans = 1;
for(var i=1; i<n.length; i++) {
    if(n[i] != n[i-1]) ans++;
}
var add = 0;
if(n.length == 1) {
    print(1);
} else {
    var pos = -1;
    for(var i=1; i<n.length; i++) {
        if(n[i] == n[i-1]) {
            if(pos == -1) {pos = i; add = 1;}
            else add = 2;
        }
    }
    print(ans+add);
}

var x = readline();
var n = readline();
var ans = 1;
for(var i=1; i<n.length; i++) {
    if(n[i] != n[i-1]) ans++;
}
var add = 0;
if(n.length == 1) {
    print(1);
} else {
    if(n[0] == n[1]) add = 1;
    if(n[n.length-1] == n[n.length-2]) add = 1;
    var pos = -1;
    for(var i=1; i<n.length; i++) {
        if(n[i] == n[i-1]) {
            if(pos == -1) pos = i;
            else add = 2;
        }
    }
    print(ans+add);
}

var x = readline();
var n = readline();
var ans = 1;
for(var i=1; i<n.length; i++) {
    if(n[i] != n[i-1]) ans++;
}
var add = 0;
if(n.length == 1) {
    print(1);
} else {
    if(n[0] == n[1]) add = 1;
    if(n[n.length-1] == n[n.length-2]) add = 1;

    for(var i=1; i<n.length-1; i++) {
        if(n[i] == n[i-1] && n[i+1] == n[i]) add = 2;
    }
    print(ans+add);
}

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()

function main() {
  const n = getInt()
  const s = getLine()[0]

  let lastZero = 0
  let lastOne = 0
  const L = [[0,0]]
  const R = []
  R[n] = [0, 0]

  for (let i = 0; i < n; ++i) {
    let best = 0
    L[i + 1] = []
    if (s[i] === '0') {
      best = lastOne + 1
      L[i + 1][0] = best
      L[i + 1][1] = lastZero + 1
      lastZero = best
    } else {
      best = lastZero + 1
      L[i + 1][0] = lastOne + 1
      L[i + 1][1] = best
      lastOne = best
    }
  }

  lastZero = lastOne = 0
  for (let i = n - 1; i >= 0; --i) {
    let best = 0
    R[i] = []
    if (s[i] === '0') {
      best = lastOne + 1
      R[i][0] = best
      R[i][1] = lastZero + 1
      lastZero = best
    } else {
      best = lastZero + 1
      R[i][0] = lastOne + 1
      R[i][1] = best
      lastOne = best
    }
  }

  let ans = 0
  let i = 0
  while (i < n) {
    let j = i + 1
    const a = i
    while (j < n && s[j - 1] !== s[j]) {
      j ++
    }
    const b = j - 1
    const cur = Math.max(b - a - 2, 0)
    const best = calc(b, a, s, L, R)
    ans = Math.max(ans, cur + best)
    i ++
  }
  print(ans)
}

function calc(a, b, s, L, R) {
  const left = (s[a] != '0' ? 0 : 1)
  const right = (s[b] != '0' ? 1: 0)

  return Math.max(R[a][left] + L[b][right], R[a][!left ? 1 : 0] + L[b][!right ? 1 : 0])
}

var input = readline().split(' ').map(Number), n = input[0];
var str = readline();
var arr = str.split('');

if (str.indexOf('000') >= 0) {
    var k = str.indexOf('000');
    arr[k+1] = '1';
} else if (str.indexOf('111') >= 0) {
    k = str.indexOf('111');
    arr[k+1] = '0';
} else if (str.substr(0,2) == '00') {
    arr[0] = '1';
} else if (str.substr(0,2) == '11') {
    arr[1] = '0';
} else if (str.substr(-2,2) == '00') {
    arr[arr.length - 1] = '1';
} else if (str.substr(-2,2) == '11') {
    arr[arr.length - 1] = '0';
}
var counter = 0;
for (var i = 1; i < str.length; i++) {
    if (arr[i] != arr[i-1]) counter++;
}
write(counter+1);


"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let spell = iInpArr();
    let sum = arr.reduce((acc, cur) => acc + cur, 0);
    spell.sort((a, b) => b - a);
    let ans = 0;
    for (let i = 1; i < n; i++) ans += spell[i];
    console.log(sum + ans);
  }
};
solve();

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(),
        b = rns();
  let res = 0;
  for (let l = 0, r = n - 1; l <= r;) {
    if (b[l] < b[r]) {
      res += a[l];
      a[l + 1] += b[l];
      l++;
    } else {
      res += a[r];
      a[r - 1] += b[r];
      r--;
    }
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

function sum(arr) {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}

function solve(a, b) {
    var sumHealths = sum(a);
    var sumDebuffs = sum(b);
    var maxDebuff = Math.max.apply(null, b);

    cl(sumHealths + sumDebuffs - maxDebuff);
}

function main() {
    const numOfCases = rlsn();

    for (let testCase = 0; testCase < numOfCases; testCase++) {
        const num = rlsn();
        const l1 = rlarrn();
        const l2 = rlarrn();

        solve(l1, l2);
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inStr = '';
let curLine = 0;
const cl = console.log;

process.stdin.on('data', function(inStdin) {inStr += inStdin;});
process.stdin.on('end', function() {inStr = inStr.split('\n');main();});

function readline() {return inStr[curLine++].replace(/\s+$/g, '');}
function rlsn() {return Number(readline());}
function rlarrstr() {return readline().split(' ');}
function rlarrn() {return rlarrstr().map(Number);}
function makeFreqMap(str) {const m={};for (let char of str) m[char]=m[char]+1||1;return m;}

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const n = parseInt(input[index]);
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const b = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      a,
      b,
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, a, b } = testCase;

  let result = 0;
  let maxi = 0;
  for (let i = 0; i < n; i++) {
    result += a[i] + b[i];
    if (b[i] > maxi) maxi = b[i];
  }
  result -= maxi;
  console.log(result);
}

parseInput();

testCases.forEach(solution);

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start(){
	const T = parseInt(lines[0])
	let line = 1
	for(let t = 1; t <= T; t++) {
	    const n = parseInt(lines[line++].trim().split(' ')[0], 10)
	    let result = 0;
	    let max = 0;
	    lines[line++].trim().split(' ').map(x => {
	        const a = parseInt(x, 10)
	        result += a;
	    })
	    lines[line++].trim().split(' ').map(x => {
	        const b = parseInt(x, 10)
	        result += b;
	        if (max < b)
	            max = b
	   })
	    console.log(result - max)
	}
}

/*
** Template
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});

process.stdin.on("end", (_) => {
    inputString = inputString
        .trim()
        .split("\n")
        .map((string) => {
            return string.trim();
        });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        let monsters = readline().split(' ').map( Number )
        let spells   = readline().split(' ').map( Number )

        // let res = parseInt(readline())
        // console.log(res , solve(n, monsters, spells))
        console.log(solve(n, monsters, spells))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n, monsters, spells) => {
    if ( n === 1 ) return monsters[0]

    let i = -1, totalTime = 0, maxSpell = Number.MIN_SAFE_INTEGER
    while( ++i < n ){
        totalTime += monsters[i] + spells[i]
        maxSpell = Math.max( maxSpell, spells[i] )
    }

    return totalTime - maxSpell
}

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const a = readLine().split(' ').map(p => +p);
        const b = readLine().split(' ').map(p => +p);
        let result = myFunc(n, a, b);
        console.log(result);
    }
}

function myFunc(n, a, b){

    let sumA = 0;
    let sumB = 0;
    let maxB = 0;

    for(let i = 0; i < n; i++){
        sumA += a[i];
        sumB += b[i];
        if(b[i] > maxB) maxB = b[i];
    }

    return sumA + sumB - maxB;

}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var n = Number(readline()); // num of monsters
    var a = readline().split(' ').map(Number); // array of healthpools
    var b = readline().split(' ').map(Number); // array of debuffs

    var seconds = process(a, b);
    print(seconds);
}

function sum(arr) {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}

function process(a, b) {
    var sumHealths = sum(a);
    var sumDebuffs = sum(b);
    var maxDebuff = Math.max.apply(null, b);

    return sumHealths + sumDebuffs - maxDebuff;
}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var n = Number(readline()); // num of monsters
    var a = readline().split(' ').map(Number); // array of healthpools
    var b = readline().split(' ').map(Number); // array of debuffs

    var seconds = process(a, b);
    print(seconds);
}

function process(a, b) {
    var result = a.reduce((acc, h) => acc + h, 0);
    var resultB = b.reduce((acc, h) => acc + h, 0);
    var maxB = Math.max(...b);

    return result + resultB - maxB;
}

/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function print(str) {
    console.log(str);
}
// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, h, b) {
    let sum = 0;
    let max = Number.MIN_SAFE_INTEGER;
    for(let i = 0; i < n; i++) {
        sum += h[i] + b[i];
        max = Math.max(max, b[i]);
    }
    sum -= max;
    print(sum);

}
function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var h = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        var b = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, h, b);
    }
}

/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin2(n, h, b) {
    let blist = b.map((value, index) => [value, index]);
    blist.sort((a,b) => { return a[0] - b[0]});
    //print(blist.join(' '));
    let used = new Array(n).fill(false);
    let sum = 0;
    for(let i = 0; i < n; i++) {
        used[blist[i][1]] = true;
        sum += h[blist[i][1]];
        let next = blist[i][1] + 1;
        while(next < n) {
            if(used[next] == false) {
                h[next] += blist[i][0];
                break;
            }
            next++;
        }
        let pre = blist[i][1] - 1;
        while(pre >= 0) {
            if(used[pre] == false) {
                h[pre] += blist[i][0];
                break;
            }
            pre--;
        }
    }
    print(sum);
}

function begin(n, h, b) {
    let sum = 0;
    let used = new Array(n).fill(false);
    let index = 0;
    while(index < n) {
        let min = Number.MAX_SAFE_INTEGER;
        let minPos = -1;
        let first = -1, last = n - 1;
        for(let i = 0; i < n; i++) {
            if(used[i] == false) {
                if(first == -1) {
                    first = i;
                }
                if(b[i] < min) {
                    min = b[i];
                    minPos = i;
                }
                last = i;
            }
        }
        //
        let choose = -1;
        if( 2 * min < b[first] && 2 * min < b[last]) {
            //choose min
            choose = minPos;
        } else if(b[first] < b[last]) {
            //choose first
            choose = first;
        } else {
            //choose last
            choose = last;
        }
        used[choose] = true;
        sum += h[choose];
        let next = choose + 1;
        while(next < n) {
            if(used[next] == false) {
                h[next] += b[choose];
                break;
            }
            next++;
        }
        let pre = choose - 1;
        while(pre >= 0) {
            if(used[pre] == false) {
                h[pre] += b[choose];
                break;
            }
            pre--;
        }
        index++;
    }
    print(sum);

}
function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var h = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        var b = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, h, b);
    }
}

/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin2(n, h, b) {
    let blist = b.map((value, index) => [value, index]);
    blist.sort((a,b) => { return a[0] - b[0]});
    //print(blist.join(' '));
    let used = new Array(n).fill(false);
    let sum = 0;
    for(let i = 0; i < n; i++) {
        used[blist[i][1]] = true;
        sum += h[blist[i][1]];
        let next = blist[i][1] + 1;
        while(next < n) {
            if(used[next] == false) {
                h[next] += blist[i][0];
                break;
            }
            next++;
        }
        let pre = blist[i][1] - 1;
        while(pre >= 0) {
            if(used[pre] == false) {
                h[pre] += blist[i][0];
                break;
            }
            pre--;
        }
    }
    print(sum);
}

function begin(n, h, b) {
    let sum = 0;
    let used = new Array(n).fill(false);
    let index = 0;
    while(index < n) {
        let min = Number.MAX_SAFE_INTEGER;
        let minPos = -1;
        let first = -1, last = n - 1;
        for(let i = 0; i < n; i++) {
            if(used[i] == false) {
                if(first == -1) {
                    first = i;
                }
                if(b[i] < min) {
                    min = b[i];
                    minPos = i;
                }
                last = i;
            }
        }
        //
        let choose = -1;
        if( 2 * min < b[first] && 2 * min < b[last]) {
            //choose min
            choose = minPos;
        } else if(b[first] < b[last]) {
            //choose first
            choose = first;
        } else {
            //choose last
            choose = last;
        }
        //left 2 select min h
        if(first + 1 == last) {
            if(h[first] < h[last]) {
                choose = first;
            } else {
                choose = last;
            }
        }

        used[choose] = true;
        sum += h[choose];
        let next = choose + 1;
        while(next < n) {
            if(used[next] == false) {
                h[next] += b[choose];
                break;
            }
            next++;
        }
        let pre = choose - 1;
        while(pre >= 0) {
            if(used[pre] == false) {
                h[pre] += b[choose];
                break;
            }
            pre--;
        }
        index++;
    }
    print(sum);

}
function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var h = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        var b = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, h, b);
    }
}

/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, h, b) {
    let blist = b.map((value, index) => [value, index]);
    blist.sort((a,b) => { return a[0] - b[0]});
    //print(blist.join(' '));
    let used = new Array(n).fill(false);
    let sum = 0;
    for(let i = 0; i < n; i++) {
        used[blist[i][1]] = true;
        sum += h[blist[i][1]];
        let next = blist[i][1] + 1;
        while(next < n) {
            if(used[next] == false) {
                h[next] += blist[i][0];
                break;
            }
            next++;
        }
        let pre = blist[i][1] - 1;
        while(pre >= 0) {
            if(used[pre] == false) {
                h[pre] += blist[i][0];
                break;
            }
            pre--;
        }
    }
    print(sum);
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var h = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        var b = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, h, b);
    }
}

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      while (l <= r && a[l] > k) l++;
      if (l <= r && a[l] <= k) ans++;
    }
    return ans >= k;
  };
  let l = 0,
      r = n;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var n = Number(readline()); // num of monsters
    var a = readline().split(' ').map(Number); // array of healthpools
    var b = readline().split(' ').map(Number); // array of debuffs

    var seconds = process(a, b);
    print(seconds);
}

function processCopy(item, i) {
    return i === 0 || i === b.length - 1 ? item : item * 2;
}

function process(a, b) {
    var result = a.reduce((acc, h) => acc + h, 0);

    while (b.length) {
        var copy = Object.assign([], b);
        copy = copy.map(processCopy);

        var indexOfLeast = copy.indexOf(Math.min(...copy));

        if (b.length > 1) {
            result += copy[indexOfLeast];
        }
        b.splice(indexOfLeast, 1);
    }

    return result;
}


readline();
var nums = readNums();
var res = [];

for (var i = 0; i < nums.length; i++) {
    res[nums[i] - 1] = i + 1;
}
print(res.join(' '));

function readNums() {
    return readline().split(' ').map(v => v - 0);
}

var n=+readline();
var p=readline().split(' ').map(function(v){return+v;});
var ans=[];
p.forEach(function(v,i){
	ans[v]=i+1;
});
ans.shift();
print(ans.join(' '));

var n=readline();
var str = readline().split(" ");
var m =[];
	for (var i=0; i<n; i++){
	   m[str[i]]= i+1;
	}

print(m.join(" "));

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
for(var i=1 ; i<=n ; i++){
    write((input.indexOf(i)+1) + ' ')
}
print();

step = readline();
var x = readline().split(" ");
var str = "";
for (i=1;i<=step;i++){
    str += (x.indexOf(i.toString())+1)+" ";
}
print(str);

    var n       = parseInt(readline()),
        friends = readline().split(' '),
        arr     = []
    friends.forEach(function(v, i) {
        friends[i] = parseInt(v);
    })

    for(var i = 1; i <= n; i++){

        arr.push(friends.indexOf(i) + 1);

    }

    arr = arr.join(' ');

    print(arr);

var n=+readline();
var p=readline().split(" ").map(function(x){return +x});
ans=[];
for(var i = 0; i<p.length; i++){
    ans[p[i]]=i+1;
}
print(ans.join(" "));

var num = readline(),
	giveGifts = readline().split(' ').map(c => c*1),
	takeObj = {},
	output = [];

giveGifts.forEach(function(current,index){
	takeObj[current] = index+1;
});

for(var i = 1; i <= num; i++){
	output.push(takeObj[i]);
}

print(output.join(' '));

var n = parseInt( readline() );
var inputNumbers = readline().split(' ');
var perm =[];
for(var k=1; k<=n; k++){
    var number = parseInt(inputNumbers[k-1]);
    perm[number] = k;
}
var result = "";
for(var j=1;j<=n;j++){
    result = result + perm[j]+" ";
}
print(result);

var number = Number(readline())
  var numbers = readline().split(' ').map(Number)

  var arr = new Array(number).fill(0)
  for(var i = 0; i < number; i++) {
    arr[numbers[i] - 1] = i + 1
  }

  print(arr.join(' '))

var firstLine = readline().toLowerCase();
var secondLine = readline().toLowerCase();

var obj = secondLine.split(' ').reduce((a, b, index) => (a[index + 1] = b, a), {});
var result = Object.keys(obj).sort(function(a, b){ return obj[a] - obj[b] }).join(' ');

print(result);

var n = readline().split(" ").map(function (x) { return parseInt(x); });
    var tmp = readline().split(" ").map(function (x) { return parseInt(x); });

    var res = []

    for (var i = 1; i <= n; i++) {
        res[tmp[i - 1]] = i;
    }

    res = res.slice(1).toString();
    // console.log(tmp[3], typeof tmp);
    res = res.replace()
    print(res.split(',').join(' '));

var input = parseInt(readline());
var gifts = readline().split(" ").map(x=>parseInt(x));
var output = [];
for(var i=1; i<=input; i++){
    output.push(gifts.indexOf(i)+1);
}
print(output.join(" "))

;(function () {

	readline();
	var p = readline().split(' ').map(function (x) { return +x; });
	var t = new Array(p.length);

	for (var i = 0; i < p.length; i++) t[p[i]] = 1 + i;

	print(t.join(' '));

}).call(this);

var n = parseInt(readline());
var a = readline().split(' ');
var s=new Array(n);

for(var i=0;i<n;i++){
        s[a[i]]=i+1;
}
for(var i=0;i<n;i++){
      print(s[i+1]);
}

var res = sol(readline());
print(res);

function sol(line) {
    var input = line.split(" ");

    var n = input[0];

    var giveTo = readline().split(" ");
    var recieveFrom = [];

    for (var i = 0; i < n; i++) {
        recieveFrom[giveTo[i] - 1] = i + 1;
    }

    return recieveFrom.join(" ");
}

const readline = require('readline');
let inputs = [];
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {
	const n = inputs[0].split(' ').map(function (a) { return parseInt(a); });
    const k = inputs[1].split(' ').map(function (a) { return parseInt(a); });
    console.log(solution(n, k));

})

// End of interface

const solution = (n, presentsArray) => {
	let resArray = [];
	for (let j = 1; j<=n; j++){
		resArray.push(presentsArray.indexOf(j) + 1);
	};
	return resArray.join(' ');
};

let stdin = process.stdin;
stdin.setEncoding('utf8');
stdin.on('data', function (data) {
    let input = data.split('\n');
    let n = input[0].split(' ').map(function (a) { return parseInt(a); });
    let k = input[1].split(' ').map(function (a) { return parseInt(a); });
    let result = solution(n, k);
    console.log(result);
});

// End of interface

const solution = (n, presentsArray) => {
	let res = '';
	let presentsArrayOfObjects = [];
	for (let j = 0; j<n; j++){
		presentsArrayOfObjects.push({p:presentsArray[j], i:j+1})
	}
	let presentsAOOsortedByP = 	presentsArrayOfObjects.sort(function(obj1, obj2){ return obj1.p - obj2.p})
	let resArray =[];
	for (let k =0; k<n; k++){
		resArray.push(presentsAOOsortedByP[k].i)
	}
	res = resArray.join(' ');
	return res;
};

var result

var n = +readline()
var p = readline().split(' ').map(function (x) { return +x })
var ans = []
for (var i = 0; i < p.length; i++) {
ans[p[i]] = i + 1
}

ans.shift()
result = ans.join(' ')
print(result)

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

let friendCount, friendNums = [];

rl.on('line', n => {
  if (!friendCount) { friendCount = n } else {
    n = n.split(' ').map(Number);
    let min = Math.min(...n);
    let max = Math.max(...n);
    for (min; min <= max; min++) {
      friendNums.push(n.indexOf(min) + 1);
    }
    console.log(...friendNums);
    rl.close();
  }
});

function main() {
    // write code here:
    var n = Number(stdin[0]);
    var arr=stdin[1].split(' ').map(Number);
    var obj={};
    var newArr=[];
    for(let i=0;i<n;i++){
        obj[arr[i]]=i+1;
    }
    for(var key in obj){
        newArr.push(obj[key]);
    }
    console.log(newArr.join(' '));
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {
    stdin.push(line);
});
rl.on('close', main);

function main() {
    // write code here:
    var n = Number(stdin[0]);
    var arr=stdin[1].split(' ').map(Number);
    var newArr=[];
    for(let i=0;i<n;i++){
        newArr.push(arr.indexOf(i+1)+1);
    }
    console.log(newArr.join(' '));
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {
    stdin.push(line);
});
rl.on('close', main);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = nextIntArray();
  var output = new Array(N);
  for(var i = 0; i < N; i++){
    output[list[i] - 1] = i + 1;
  }
  myout(myconv(output, 8));
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let n = Number(readLine());
  const a = readLine().split(' ').map(_a => Number(_a));
  const b = [];
  a.forEach((_a, i) => b[_a - 1] = i + 1);
  console.log(b.join(' '));
}

const readline = require('readline');

let inputs = [];

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    const friends = inputs[1].split(' ');
    let result = [];

    for (let i = 0; i < friends.length; i++) {
        const position = friends.indexOf((i + 1).toString());
        result[i] = position + 1;
    }

    console.log(result.join(' '))

})

var n = readline();
var a = [];
var output=[];
var x;
a = readline()
.split(" ")
.map((a) => parseInt(a));
for(var i=1;i<=n;i++){
   x= a.indexOf(i)
   output.push(x+1)
}
print(output.join(" "))

readline();
var data = readline().split(' ').map(Number);
var result = [];

for(var i = 0; i < data.length; i++)
{
	result[data[i]] = i + 1; // +1 because the index of problem started from 1 instead of 0
}

result.splice(0, 1); // must be spliced since result started from index 1 instead of 0
print(result.join(' '));

'use strict';

(function() {
    let n = parseInt(readline());
    let a = readline().split(' ').map(value => parseInt(value));
    let b = new Array(n);

    a.map((value, index) => {
      b[value - 1] = index + 1;
    });

    write(b.join(' '));

})();

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  const p = readline().split(' ').map(x => parseInt(x));
  const m = new Map();
  for (let i = 0; i < n; i++) {
    m.set(p[i], i + 1);
  }
  const a = [];
  for (let i = 0; i < n; i++) {
    a.push(m.get(i + 1));
  }
  print(a.join(' '));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let counter = 0;

rl.on('line', (d) => {
  if (counter === 0) {
    counter++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const arr2 = [];

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[j] == i + 1) {
        arr2.push(j + 1);
      }
    }
  }

  console.log(arr2.join(' '));

  counter++;
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function min(a,b) {
    if(a > b) return b;
    else return a;
}
function main() {
        let n  = parseInt(readline());
        let p = readint();
        let mynew = [];
        p.forEach((v, k) => {
            mynew[v - 1] = k + 1;
        });
        mynew.forEach((v) => {
            write(v + " ");
        });
}

const readLine = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const friends = input[1].split(' ').map(x => parseInt(x));
  const answer = [];

  friends.forEach((x, i) => {
    answer[x-1] = i+1;
  });

  console.log(answer.join(' '));
});

const readline = require('readline');
let inputs = [];
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
rl.on('line', lineInput => {
    inputs.push(lineInput)
})
rl.on('close', () => {
		const n = inputs[0].split(' ').map(function (a) { return parseInt(a); });
    const k = inputs[1].split(' ').map(function (a) { return parseInt(a); });
    console.log(solution(n, k));
})

const solution = (n, presentsArray) => {
	let resArray = [];
	for (let j = 1; j<=n; j++){
		resArray.push(presentsArray.indexOf(j) + 1);
	};
	return resArray.join(' ');
};

var n = Number(readline());
var s = readline().split(' ');
var friends = [];

for (var i = 0; i < s.length; i++) {
    friends[s[i]-1] = i+1;
}
print(friends.join(' '));

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
});

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    const ints = Array.from(input[1].split(' '), x => parseInt(x));
    const outs = [...ints];
    ints.forEach((v, i) => {
        outs[v - 1] = ints.indexOf(v) + 1;
    })

    console.log(outs.join(' '));
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    // if(Array.isArray(inputString)) inputString = inputString.join('\n');
    inputString += inputStdin;
    // inputString = inputString.trim().split('\n').map(string => {
    //     return string.trim();
    // });

    // main();
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readAsInt(){
  return parseInt(readline());
}

function readAsIntList(){
  return readline().trim().split(' ').filter(i => i).map(i => parseInt(i));
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let l = readAsInt();
  let list = readAsIntList();
  let result = [];
  for(let i = 1; i <= list.length; i++){
    result[list[i-1]-1] = i;
  }
  console.log(result.join(' '));
}

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0;
});
for (let i = 1; i < txt.length; i += 2) {
    doit(txt[i].split(" ").filter(data => {
        return data.length > 0;
    }).map(data => {
        return data * 1;
    }));

}

function doit(arr) {
    let tab = [];
    arr.forEach((data, index) => {
        tab[data - 1] = index + 1;
    });
    console.log(tab.join(" "));
}

// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {
    let inputs = str.trim().split('\n');
    let frns = inputs[1].trim().split(' ');
    let auxArray = [];
    for (let i = 0; i < frns.length; i++) {
        auxArray[frns[i]] = i + 1;
    }

    return auxArray.join(' ').trim().toString();
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
let secondLine = input[1].split(' ');
const n = parseInt(input[0], 10);
secondLine = secondLine.map((el) => parseInt(el, 10));
let text = '';
for (let i = 1; i< n + 1; i++) {
  text += `${secondLine.indexOf(i) + 1} `
}
text = text.slice(0, text.length-1)
console.log(text);
});

const readLine = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
});

const input = [];
readLine.on('line', line => input.push(line));
const gifts = () => {
        const a = input[1].split(' ').map(x => +x);
    const b = Array(a.length);
    let n = 1;
    for (const x of a) {
        b[x - 1] = n;
        n++;
    }
    console.log(b.join(' '));
};
readLine.on('close', gifts);

n = readline().split(' ').map(Number);
data = readline().split(' ').map(Number);
result = []
for (i=0;i<data.length;i++){
	result[data[i]] = i+1;
}
result.splice(0,1);
print(result.join(' '));

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    let n = parseInt(readLine());
    let arr = readLine()
        .split(' ')
        .map(value => parseInt(value));

    let ans = [];
    for (var i = 1; i <= n; i++) {
        ans.push(arr.indexOf(i) + 1);
    }
    console.log(ans.join(' '));
}

var line1 = readline();
var n = parseInt(line1);

var line2 = readline().split(' ').map(Number);

var str = '';

for(i=1;i<n+1;i++){
    for(j=0;j<n;j++){
	if(line2[j]===i){
	    str += (j+1);
	    str += ' ';
	    continue;
	}
    }
}

print(str);

var n = readline();
var d = readline().split(' ').map(Number);
var p = [];
for (i=0; i<d.length; i++){
    p[d[i]]= i+1;
}
write(p.join(' '));

var getNums = function () {
    return readline().split(' ').map(function (a) { return parseInt(a) });
};

//136A
//Local attempts - 2
var n = readline();
var data = getNums();
var res = [];
for(var i = 0; i < n; i++) {
    res[data[i]] = i + 1;
}
print(res.join(' '));

var n = +readline();
var gifts = readline().split(" ");
var result = [];
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift,index) => {
    if(gift == i){
      result.push(index);
    }
  });
}
result.forEach((gift) => print(gift+1));

/*x=readline();
var a = [];
a.push(readline());
 a.push(readline());
 a.push(readline());
/*a = a.sort(function(a,b){
    return a-b;
});*/
/*
var max_stack = [];
//(a+b)*c
max_stack.push(parseInt((parseInt(a[0])+parseInt(a[1]))*parseInt(a[2])));
//a*(b+c)
max_stack.push(parseInt(parseInt(a[0])*((parseInt(a[1])+parseInt(a[2])))));
//a*b*c
max_stack.push(parseInt(parseInt(a[0])*parseInt(a[1])*parseInt(a[2])));

//a*b+c

max_stack.push(parseInt(parseInt(a[0])*parseInt(a[1])+parseInt(a[2])));
//a+b*c
max_stack.push(parseInt(parseInt(a[0])+parseInt(a[1])*parseInt(a[2])));
//a+b+c
max_stack.push(parseInt(parseInt(a[0])+parseInt(a[1])+parseInt(a[2])));

var maximus=-999;
for(i=0;i<max_stack.length;i++)
{
  if(maximus<max_stack[i])
  {
      maximus=max_stack;
  }
}
max_stack=max_stack.sort(function(a,b){
    return b-a;
});
print(max_stack[0]);

//for(i=0;i<a.length;i++)
//print(a[0]);

/*var k = readline();
var c = readline();
var len = 0;
for(i=c.length-1,j=0;i>=0,j<k.length;i--,j++)
{
   if(k[i]==c[j]){
       len++;
   }
}
 if(len==c.length)
 {
     print('YES')
 }
 else
 print('NO')*/

/*
var n = readline();
var m = readline().split(' ').map(Number);
var len = 1;
var max = 1;
for(i=0;i<m.length;i++)
{
   if(m[i]-m[i-1]>=0) {
    len++;
    max=Math.max(max,len);
   }
    else
    {
        len=1;
    }
}

print(max)
 */

 var n = readline();
 var d = readline().split(' ').map(Number);
 var c = [];
 for(i=0;i<d.length;i++)
 {
     c[d[i]]=i+1;
 }

 write(c.join(' '));

var n=readline();
var str = readline().split(" ");
var m =[];
	for (var i=0; i<n; i++){
	   m[str[i]]= i+1;
	}

print(m.join(" "));

(function() {
    'use strict';
    let n = readline();
    let x = readline().split(' ').map(Number);
    let i = 0;
    var y = new Array(n);
    var z;
    for (i; i < n; i++) {
        z = x[i] - 1;
        y[z] = i + 1;
    }
    print(y.join(" "));
}());

var n = parseInt(readline());
var g = (function(a) { for (var i=0; i<a.length; i++) a[i] = parseInt(a[i]); return a; })(readline().split(" "));
var r = new Array(n);

for (var i=0; i<g.length; i++) {
	r[g[i]-1] = i+1;
}

print(r.join(" "));

var n = parseInt(readline());
var line = readline().split(' ');
var gifts = {};
for(var i = 0; i < n; i++)
    gifts[line[i] - 1] = i + 1;

    var o = ''
for(var key in gifts)
     o += gifts[key] + ' ';

     print(o.trim());

/* TEST CASE
input
4
2 3 4 1
output
4 1 2 3

input
3
1 3 2
output
1 3 2

input
2
1 2
output
1 2

*/
function main() {
	var n = parseInt(readline());
	var giveTo = new Array(n);
	var i;
	var splitted = readline().split(' ');
	for (i = 0; i < n; i++) {
		giveTo[parseInt(splitted[i]) - 1] = i + 1;
	}

	print(giveTo.join(' '));
}

main();

var total = parseInt(readline());
var vals = readline().split(" ").map(Number);

var ans = [];

for (var i = 0; i < vals.length; i++) {
    ans[vals[i] - 1] = i + 1;
}

print(ans.join(" "));

readline();
n = readline().split(' ');
var f = []
for(i= 0 ; i < n.length ; i++)
{ f[parseInt(n[i])] = i + 1;}
print(f.join(' '))

//var input = "4\n2 3 4 1";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function main(){
    readline();
    var arr = readline().split(' ');
    var ans = new Array(arr.length + 1);
    var str = "";
    for(var i = 0; i < arr.length; i++)
        ans[arr[i]] = i + 1;
    for(var i = 1; i < ans.length; i++)
        str += ans[i] + " ";
    print(str);
}
main();

var n = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var res = new Array(n);
for (var i = 0; i < a.length; i++) {
	res[a[i]] = i + 1;
}
print (res.join(' '));

var computeFriends = function(arr)
    {
        var min = 1, arrres = [];
        var toNumArr = function(arr)
        {
            arr = arr.split(' ');
            for (var i = 0 ; i <= arr.length - 1; i++)
            {
                arr[i] = +arr[i];
            }
            return arr;
        }
        arr = toNumArr(arr);
        for (var counter = 0; counter <= arr.length - 1;counter++)
        {
            if (arr[counter] === min)
            {
                min++;
                arrres.push(counter + 1);
                counter = -1;
            }
        }
        return arrres.join(' ');
    }
var num = readline();
print(computeFriends(readline()));

var n = parseInt(readline(), 10)
    p = readline().split(' ').map(el => parseInt(el, 10)),
    result = [],
    p_i = 0;

for(var i=0; i<p.length; i++) {
    p_i = p[i]-1;
    result[p_i] = i + 1;
}

print(result.join(' '));

var n = parseInt(readline());
var array = readline().split(" ").map(function convert(value) {return +value; });
var reverse = [];

while(--n + 1)
	reverse[n] = array.indexOf(n + 1) + 1

print(reverse.join(" "));

(function main() {
    var count = parseInt(readline());

    var input = readline().trim().split(' ').map(Number);

    var output = [];
    for (var i = 0; i < count; i++){
        output[input[i] - 1] = i + 1;
    }

    var result = "";
    for (var i = 0; i < count; i++){
        result += " " + output[i];
    }

    print(result.trim());

    return 0;
})();

const readline = require('readline');
let inputs = [];
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {
	const n = inputs[0].split(' ').map(function (a) { return parseInt(a); });
    const k = inputs[1].split(' ');
    console.log(solution(n, k));

})

// End of interface

const solution = (n, presentsArray) => {
	let resArray = [];
	for (let j = 1; j<=n; j++){
		resArray.push(presentsArray.indexOf(j) + 1);
	};
	return resArray.join(' ');
};

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

let friendCount, friendNums = [];

rl.on('line', n => {
  if (!friendCount) { friendCount = n } else {
    n = n.split(' ').map(Number);
    let min = Math.min(...n);
    let max = Math.max(...n);
    for (min; min <= max; min++) {
      friendNums.push(n.indexOf(min) + 1);
    }
    console.log(friendNums);
    rl.close();
  }
});

const readline = require('readline');

let inputs = [];

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    const friends = inputs[1].split(' ');
    const nOfFriends = friends.length;
    let result = [];

    for (let i = 0; i < nOfFriends; i++) {
        const Pi = Math.floor(Math.random() * friends.length);
        const pickedOne = friends.splice(Pi, 1)[0];
        result.push(pickedOne);
    }

    console.log(...result);

})

const readline = require('readline');

let inputs = [];

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    const friends = inputs[0].split(' ');
    let result = [];

    for (let i = 0; i < friends.length; i++) {
        const position = friends.indexOf((i + 1).toString());
        result[i] = position + 1;
    }

    console.log(result.join(' '))

})

const readline = require('readline');

let inputs = [];

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    const friends = inputs[0].split(' ');
    const nOfFriends = friends.length;
    let result = [];

    for (let i = 0; i < nOfFriends; i++) {
        const Pi = Math.floor(Math.random() * friends.length);
        const pickedOne = friends.splice(Pi, 1)[0];
        result.push(pickedOne);
    }

    console.log(...result);

})

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
});

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    const ints = Array.from(input[1].split(' '), x => parseInt(x));
    const outs = [...ints];
    ints.forEach((v, i) => {
        console.log(v);
        outs[v - 1] = ints.indexOf(v) + 1;
    })

    console.log(outs);
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    let n = parseInt(readLine());
    let arr = readLine()
        .split(' ')
        .map(value => parseInt(value));

    let ans = [];
    for (var i = 1; i <= n; i++) {
        ans.push(arr.indexOf(i) + 1);
    }
    console.log(ans);
}

var n=+readline();
var p=readline().split(' ').map(function(v){return+v;});
var ans=[];
p.forEach(function(i,v){
	ans[v]=i+1;
});
ans.shift();
print(ans.join(' '));

step = readline();
var x = readline().replace(/ /g,"");
var str = "";
for (i=1;i<=step;i++){
    str += (x.indexOf(i)+1)+" "
}
print(str)

step = readline();
var x = readline().replace(/ /g,"");
var str = "";
for (i=1;i<=step;i++){
    str += ((x.indexOf(i))+1)+" "
}
print(str)

var n=+readline();
var p=readline().split(" ").map(function(x){return +x});
ans = [];
for(var i = 0; i<p.length; i++){
    ans[p[i]] = i + 1;
}
print(ans.join());

var computeFriends = function(arr)
    {
        var min = 1, arrres = [];
        var toNumArr = function(arr)
        {
            arr = arr.split(' ');
            for (var i = 0 ; i <= arr.length - 1; i++)
            {
                arr[i] = +arr[i];
            }
            return arr;
        }
        arr = toNumArr(arr);
        for (var counter = 0; counter <= arr.length - 1;counter++)
        {
            if (arr[counter] === min)
            {
                min++;
                arrres.push(counter);
                counter = 0;
            }
        }
        return arrres.join(' ');
    }
var num = readline();
print(computeFriends(readline()));

var n = parseInt(readline());
var array = readline().split(" ").map(function convert(value) {return +value; });
var reverse = [];

while(--n + 1)
	reverse[n] = array.indexOf(n + 1) + 1

print(reverse.toString(" "));

 var a = parseInt(readline()),
        b = parseInt(readline()),
        c = parseInt(readline());
    if ((a !== 1) && (b !== 1) && (c !== 1)) {
        print(a * b * c);
    } else if ((a === 1) && (b === 1) && (c === 1)) {
        print(a + b + c);
    } else if ((a === 1) && (c === 1)) {
        print(a + b + c);
    } else if (a === 1) {
        print((a + b) * c);
    } else if (c === 1) {
        print(a * (b + c));
    } else {
        if (a > c) {
            print(a * (b + c));
        } else {
            print((a + b) * c);
        }
    }

var n = +readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  gifts.push(+readline());
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    print(gift);
    if(gift === i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = readline().split(" ");
var result = [];
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift == i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  var a = readline();
  gifts.push(a);
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    print(gift)
    if(gift === i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = readline().split(" ");
var result = [];
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift,index) => {
    if(gift == i){
      result.push(index);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  gifts.push(+readline());
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift === i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  gifts.push(+readline());
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift == i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  gifts.push(+readline());
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift === i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = [];
var result = [];
for(var i = 0; i < n; ++i){
  gifts.push(+readline());
}
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift === i){
      result.push(gift);
    }
  });
}
print(result)
result.forEach((gift) => print(gift));

var n = +readline();
var gifts = readline().split(" ");
var result = [];
for(var i = 1; i <= n; ++i){
  gifts.forEach((gift) => {
    if(gift === i){
      result.push(gift);
    }
  });
}
result.forEach((gift) => print(gift));

(function() {
    'use strict';
    let n = readline();
    let x = readline().split(' ').map(Number);
    let i = 0;
    let y = Array;
    for (i; i < n; i++) {
        y[x[i]] = i + 1;
    }
    print(y);

}());