const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        let [n, m, k] = lines[l++].trim().split(' ')
        n = +n
        m = +m
        k = BigInt(k)
        // k = +k
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
        l += m
        output[i] = solve(n, m, k, arr, edges)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, k, arr, edges) {
    if (k === 1n) {
        let min = Infinity
        for (let i = 0; i < arr.length; i++) {
            min = Math.min(min, arr[i])
        }
        return min
    }
    arr.unshift(0)
    //
    const idx = binarySearch(1, 1e9, x => {
        return !check(n, k, arr, edges, x)
    })
    return idx === 1e9 ? -1 : idx + 1
}
function check(n, k, arr, edges, x) {
    const h = new Array(n + 1).fill(-1),
        e = [],
        ne = [],
        d = new Array(n + 1).fill(-1);
    let idx = 0;
    const add = (i, j) => {
        if (d[i] === -1) d[i] = 0;
        if (d[j] === -1) d[j] = 0;
        e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
        if (arr[u] > x || arr[v] > x) continue;
        add(u, v);
    }
    let size = 0;
    const queue = [],
        dist = new Array(n + 1).fill(0);
    for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
            queue.push(u);
            dist[u] = 1;
        }
    }
    for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
            const v = e[i];
            d[v]--;
            dist[v] = Math.max(dist[v], dist[u] + 1);
            if (dist[v] == k) return true;
            if (d[v] === 0) queue.push(v);
        }
    }
    return queue.length < size
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  let buildtime = 0,
      topotime = 0,
      all = new Date().valueOf();
  const check = t => {
    let time = new Date().valueOf();
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    buildtime += new Date().valueOf() - time;
    time = new Date().valueOf();
    const topo = () => {
      let size = 0;
      const queue = [],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
      for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      if (queue.length === size) return false;
      return true;
    };
    let res = topo();
    topotime += new Date().valueOf() - time;
    return res;
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  let outs = [];
  while (l < r) {
    const mid = l + r >> 1;
    if (n === 173070) outs.push([buildtime, topotime].join(','));
    if (new Date().valueOf() - all > 2500) {
      if (n === 173070) {
        console.log(outs.join('\n'));
        console.log(new Date().valueOf() - all);
      }
    }
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(s => Number(s) - 1));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  const check = t => {
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    const topo = () => {
      let size = 0;
      const queue = [],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
      for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      if (queue.length === size) return false;
      return true;
    };
    let res = topo();
    return res;
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  while (l < r) {
    const mid = l + r >> 1;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(s => Number(s) - 1));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  const check = t => {
    const h = new Array(n).fill(-1),
          e = [],
          ne = [];
    let idx = 0;
    const add = (i, j) => {
      e[idx] = j, ne[idx] = h[i], h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    const tarjan = () => {
      const dfn = [],
            low = [],
            stack = [],
            set = new Set(),
            map = new Map(),
            fa = [];
      let loop = false;
      let time = 1,
          idx = 0;
      const dfs = u => {
        const callStack = [[u]];
        while (callStack.length) {
          let curCall = callStack[callStack.length - 1];
          while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {
            var _curCall;
            callStack.pop();
            curCall = callStack[callStack.length - 1];
            if (!curCall) continue;
            const v = curCall.pop();
            if (dfn[v] === low[v]) {
              let count = 0;
              while (true) {
                count++;
                if (count > 1) {
                  loop = true;
                  return;
                }
                const j = stack.pop();
                set.delete(j);
                map.set(j, idx);
                if (j === v) break;
              }
              idx++;
            }
            const u = fa[v];
            low[u] = Math.min(low[u], low[v]);
          }
          if (!curCall) break;
          const u = curCall[curCall.length - 1];
          if (!dfn[u]) {
            dfn[u] = low[u] = time++;
            stack.push(u);
            set.add(u);
            let nextCall = [];
            for (let i = h[u]; i !== -1; i = ne[i]) {
              const v = e[i];
              if (!dfn[v]) {
                fa[v] = u;
                nextCall.push(v);
              } else if (set.has(v)) {
                low[u] = Math.min(low[u], dfn[v]);
              }
            }
            callStack.push(nextCall);
            continue;
          } else if (set.has(u)) {
            const f = fa[u];
            low[f] = Math.min(low[f], dfn[u]);
          }
          curCall.pop();
        }
      };
      for (let i = 0; i < n; i++) {
        if (!dfn[i]) dfs(i);
        if (loop) return true;
      }
      if (k > idx) return false;
      const h1 = new Array(n).fill(-1),
            e1 = [],
            ne1 = [],
            d = new Array(idx).fill(0);
      let idx1 = 0;
      const add = (i, j) => {
        e1[idx1] = j, ne1[idx1] = h1[i], h1[i] = idx1++;
      };
      for (let u = 0; u < n; u++) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          const a = map.get(u),
                b = map.get(v);
          add(a, b);
        }
      }
      const queue = [],
            dist = new Array(idx).fill(0);
      for (let [k, v] of d.entries()) if (v === 0) {
        queue.push(k);
        dist[k] = 1;
      }
      for (let u of queue) {
        for (let i = h1[u]; i !== -1; i = ne1[i]) {
          const v = e1[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) {
            return true;
          }
          if (d[v] === 0) queue.push(v);
        }
      }
      return false;
    };
    return tarjan();
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  while (l < r) {
    const mid = l + r >> 1;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(s => Number(s) - 1));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  let buildtime = 0,
      topotime = 0,
      all = new Date().valueOf();
  const check = t => {
    let time = new Date().valueOf();
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    buildtime += new Date().valueOf() - time;
    time = new Date().valueOf();
    const topo = () => {
      let size = 0;
      const queue = [],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
      for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      if (queue.length === size) return false;
      return true;
    };
    let res = topo();
    topotime += new Date().valueOf() - time;
    return res;
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  let outs = [];
  while (l < r) {
    const mid = l + r >> 1;
    if (n === 173070) outs.push([buildtime, topotime].join(','));
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  if (n === 173070) {
    console.log(outs.join('|'));
    console.log(new Date().valueOf() - all);
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(s => Number(s) - 1));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  let buildtime = 0,
      topotime = 0,
      all = new Date().valueOf();
  const check = t => {
    let time = new Date().valueOf();
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    buildtime += new Date().valueOf() - time;
    time = new Date().valueOf();
    const topo = () => {
      let size = 0;
      const queue = [],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
      for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      if (queue.length === size) return false;
      return true;
    };
    let res = topo();
    topotime += new Date().valueOf() - time;
    return res;
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  let outs = [];
  while (l < r) {
    const mid = l + r >> 1;
    if (n === 173070) outs.push([buildtime, topotime].join(','));
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  if (n === 173070) {
    console.log(outs.join('\n'));
    console.log(new Date().valueOf() - all);
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(s => Number(s) - 1));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, k, a, edges) {
  if (k === 1) {
    console.log(Math.min(...a));
    return;
  }
  const check = t => {
    const g = Array.from({
      length: n
    }, () => []);
    for (let [u, v] of edges) {
      u--, v--;
      if (a[u] > t || a[v] > t) continue;
      g[u].push(v);
    }
    const tarjan = () => {
      const dfn = [],
            low = [],
            stack = [],
            set = new Set(),
            map = new Map(),
            loops = [],
            fa = [];
      let time = 1,
          idx = 0;
      const dfs = u => {
        const callStack = [[u]];
        while (callStack.length) {
          let curCall = callStack[callStack.length - 1];
          while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {
            var _curCall;
            callStack.pop();
            curCall = callStack[callStack.length - 1];
            if (!curCall) continue;
            const v = curCall.pop();
            if (dfn[v] === low[v]) {
              loops.push([]);
              while (true) {
                const j = stack.pop();
                set.delete(j);
                map.set(j, idx);
                loops[idx].push(j);
                if (j === v) break;
              }
              idx++;
            }
            const u = fa[v];
            low[u] = Math.min(low[u], low[v]);
          }
          if (!curCall) break;
          const u = curCall[curCall.length - 1];
          if (!dfn[u]) {
            dfn[u] = low[u] = time++;
            stack.push(u);
            set.add(u);
            let nextCall = [];
            for (let v of g[u]) {
              if (!dfn[v]) {
                fa[v] = u;
                nextCall.push(v);
              } else if (set.has(v)) {
                low[u] = Math.min(low[u], dfn[v]);
              }
            }
            callStack.push(nextCall);
            continue;
          } else if (set.has(u)) {
            const f = fa[u];
            low[f] = Math.min(low[f], dfn[u]);
          }
          curCall.pop();
        }
      };
      for (let i = 0; i < n; i++) {
        if (!dfn[i]) dfs(i);
      }
      for (let nums of loops) {
        if (nums.length > 1) return true;
      }
      const g1 = Array.from({
        length: idx
      }, () => new Set()),
            d = new Array(idx).fill(0);
      for (let [u, children] of g.entries()) {
        for (let v of children) {
          if (g1[u].has(v)) continue;
          g1[u].add(v);
          d[v]++;
        }
      }
      const queue = [],
            dist = new Array(idx).fill(0);
      for (let [k, v] of d.entries()) if (v === 0) {
        queue.push(k);
        dist[k] = 1;
      }
      for (let u of queue) {
        for (let v of g1[u]) {
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k - 1) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      return false;
    };
    return tarjan();
  };
  const max = Math.max(...a) + 10;
  let l = 0,
      r = max;
  while (l < r) {
    const mid = l + r >> 1;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  console.log(l === max ? -1 : l);
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(Number));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, m, k, a, edges) {
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of edges) {
    u--, v--;
    g[u].push(v);
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map(),
          loops = [],
          fa = [];
    let idx = 1;
    const dfs = u => {
      const callStack = [[u]];
      while (callStack.length) {
        let curCall = callStack[callStack.length - 1];
        while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {
          var _curCall;
          callStack.pop();
          curCall = callStack[callStack.length - 1];
          if (!curCall) continue;
          const v = curCall.pop();
          if (dfn[v] === low[v]) {
            loops.push([]);
            let k = loops.length - 1;
            while (true) {
              const j = stack.pop();
              set.delete(j);
              map.set(j, k);
              loops[k].push(j);
              if (j === v) break;
            }
          }
          const u = fa[v];
          low[u] = Math.min(low[u], low[v]);
        }
        if (!curCall) break;
        const u = curCall[curCall.length - 1];
        if (!dfn[u]) {
          dfn[u] = low[u] = idx++;
          stack.push(u);
          set.add(u);
          let nextCall = [];
          for (let v of g[u]) {
            if (!dfn[v]) {
              fa[v] = u;
              nextCall.push(v);
            } else if (set.has(v)) {
              low[u] = Math.min(low[u], dfn[v]);
            }
          }
          callStack.push(nextCall);
          continue;
        } else if (set.has(u)) {
          const f = fa[u];
          low[f] = Math.min(low[f], dfn[u]);
        }
        curCall.pop();
      }
    };
    for (let i = 0; i < n; i++) {
      if (!dfn[i]) dfs(i);
    }
    let res = Infinity;
    for (let nums of loops) {
      if (nums.length > 1) {
        let max = -Infinity;
        for (let i of nums) {
          max = Math.max(max, a[i]);
        }
        res = Math.min(max);
      }
    }
    return res;
  };
  let res = tarjan();
  if (k > n) {
    console.log(res === Infinity ? -1 : res);
    return;
  }
  const dfs = (i, set = new Set(), path = [], bst = new BinarySearchTree()) => {
    bst.insert(a[i]);
    path.push(i);
    set.add(i);
    if (path.length > k) {
      const b = path[path.length - k - 1];
      bst.delete(b);
    }
    if (path.length >= k) {
      res = Math.min(res, bst.getMax());
    }
    for (let j of g[i]) {
      if (set.has(j)) continue;
      dfs(j, set, path, bst);
    }
    bst.delete(a[i]);
    if (path.length > k) {
      const b = path[path.length - k - 1];
      bst.insert(b);
    }
    set.delete(i);
    path.pop();
  };
  dfs(0);
  console.log(res === Infinity ? -1 : res);
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
}

async function main(read) {
  const [n, m, k] = (await read()).split(' ').map(Number);
  const a = (await read()).split(' ').map(Number);
  const b = [];
  let tmp = m;
  while (tmp--) {
    b.push((await read()).split(' ').map(Number));
  }
  solve(n, m, k, a, b);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        let [n, m, k] = lines[l++].trim().split(' ')
        n = +n
        m = +m
        // k = BigInt(k)
        k = +k
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
        l += m
        output[i] = solve(n, m, k, arr, edges)
    }
    console.log(output.join('\n'))
// })()
})

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
    forEach(fn) {
        for (let i = this.first; i <= this.last; i++) {
            fn(this.map[i], i - this.first)
        }
    }
}

function solve(n, m, k, arr, edges) {
    arr.unshift(0)
    //
    const idx = binarySearch(1, 1e9, x => {
        // let x = 10
        return !check2(n, k, arr, edges, x)
    })
    return idx === 1e9 ? -1 : idx + 1
}
function check2(n, k, arr, edges, x) {
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (arr[u] > x || arr[v] > x) continue;
      add(u, v);
    }
    // const ins = Array(n + 1).fill(0)
    // const outs = Array(n + 1).fill(0)
    // const adj = {}
    // // const radj = {}
    // edges.forEach(([a, b]) => {
    //     if (arr[a] > x || arr[b] > x) return
    //     adj[a] = adj[a] || []
    //     adj[a].push(b)
    //     // radj[b] = radj[b] || []
    //     // radj[b].push(a)
    //     ins[b]++
    // })
        let size = 0;
      let queue = new Queue(),//[],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
      // for (let u of queue) {
      //   for (let i = h[u]; i !== -1; i = ne[i]) {
      //     const v = e[i];
      //     d[v]--;
      //     dist[v] = Math.max(dist[v], dist[u] + 1);
      //     if (dist[v] === k) return true;
      //     if (d[v] === 0) queue.push(v);
      //   }
      // }
    let level = 1n
    let count = 0
      while (queue.length) {
        // if (level >= k) return true
        const nq = new Queue()
        // while (queue.length) {
        queue.forEach(u => {
            // const u = queue.shift()
            count++
            for (let i = h[u]; i !== -1; i = ne[i]) {
              const v = e[i];
              d[v]--;
              if (level + 1n >= k) return true
              if (d[v] === 0) nq.push(v);
            }
        // }
        })
        queue = nq
        level++
      }
      return count < size

    // let q = new Queue()
    // let total = 0
    // for (let u = 1; u <= n; u++) {
    //     outs[u] = adj[u] ? adj[u].length : 0
    //     // ins[u] = (radj[u] || []).length
    //     if (ins[u] || outs[u]) {
    //         total++
    //         if (!ins[u]) q.push(u)
    //     }
    // }
    // if (!total) return false
    // let count = 0
    // const dist = Array(n + 1).fill(1)
    // while (q.length) {
    //     if (level >= k) return true
    //     const nq = new Queue()
    //     q.forEach(u => {
    //         count++
    //         ;(adj[u] || []).forEach(v => {
    //             if (!--ins[v]) nq.push(v)
    //         })
    //     })
    //     q = nq
    //     level++
    // }
    // console.log(x, level, count)
    // return count < total
}
function check(n, k, a, edges, t) {
    const h = new Array(n).fill(-1),
          e = [],
          ne = [],
          d = new Array(n).fill(-1);
    let idx = 0;
    const add = (i, j) => {
      if (d[i] === -1) d[i] = 0;
      if (d[j] === -1) d[j] = 0;
      e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;
    };
    for (let [u, v] of edges) {
      if (a[u] > t || a[v] > t) continue;
      add(u, v);
    }
    const topo = () => {
      let size = 0;
      const queue = [],
            dist = new Array(n).fill(0);
      for (let [u, count] of d.entries()) {
        if (count !== -1) size++;
        if (count === 0) {
          queue.push(u);
          dist[u] = 1;
        }
      }
    return 1
      for (let u of queue) {
        for (let i = h[u]; i !== -1; i = ne[i]) {
          const v = e[i];
          d[v]--;
          dist[v] = Math.max(dist[v], dist[u] + 1);
          if (dist[v] === k) return true;
          if (d[v] === 0) queue.push(v);
        }
      }
      if (queue.length === size) return false;
      return true;
    };
    let res = topo();
    return res;
  };
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        let [n, m, k] = lines[l++].trim().split(' ')
        n = +n
        m = +m
        k = BigInt(k)
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
        l += m
        output[i] = solve(n, m, k, arr, edges)
    }
    console.log(output.join('\n'))
// })()
})

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
}

function solve(n, m, k, arr, edges) {
    arr.unshift(0)
    //
    const idx = binarySearch(1, 1e9, x => {
        // let x = 10
        return !check(n, k, arr, edges, x)
    })
    return idx === 1e9 ? -1 : idx + 1
}
function check(n, k, arr, edges, x) {
    const ins = Array(n + 1).fill(0)
    const outs = Array(n + 1).fill(0)
    const adj = {}
    const radj = {}
    edges.forEach(([a, b]) => {
        if (arr[a] > x || arr[b] > x) return
        adj[a] = adj[a] || []
        adj[a].push(b)
        radj[b] = radj[b] || []
        radj[b].push(a)
    })
    let q = new Queue()
    let total = 0
    for (let u = 1; u <= n; u++) {
        outs[u] = (adj[u] || []).length
        ins[u] = (radj[u] || []).length
        if (arr[u] <= x) {
            total++
            if (!ins[u]) q.push(u)
        }
    }
    let level = 1n
    let count = 0
    while (q.length) {
        const nq = new Queue()
        while (q.length) {
            const u = q.shift()
            count++
            ;(adj[u] || []).forEach(v => {
                if (!--ins[v]) nq.push(v)
            })
        }
        if (level >= k) return count
        q = nq
        level++
    }
    // console.log(level, count)
    return count && count < total
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}


var prev = new Int32Array(1e5 + 5);
var diff = new Int32Array(1e5 + 5);
print(function(n, a) {

	for (var i = 1; i <= n; i++) {
		if (prev[a[i]] < 0) {
			continue;
		} else if (prev[a[i]] === 0) {
			prev[a[i]] = i;
		} else if (diff[a[i]] === 0) {
			diff[a[i]] = i - prev[a[i]];
			prev[a[i]] = i;
		} else if (diff[a[i]] === i - prev[a[i]]) {
			prev[a[i]] = i;
		} else {
			prev[a[i]] = -1;
		}
	}

	var ans = [];
	for (var i = 0; i <= 1e5; i++)
		if (prev[i] > 0) ans.push(i + ' ' + diff[i]);

	return ans.length + '\n' + ans.join('\n');

}(+readline(), ('0 ' + readline()).split(' ').map(Number)));

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}

function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const map = {};

  for (let i = 0; i < len; i++) {
    const num = arr[i];
    if (!map[num]) {
      map[num] = { count: 1, index: i, diff: 0, status: true };
    } else {
      let { count, index, diff, status } = map[num];
      if (status) {
        if (count === 1) {
          map[num] = { count: count + 1, index: i, diff: i - index, status: true };
        } else {
          map[num] = { count: count + 1, index: i, diff: i - index, status: diff === i - index };
        }
      }
    }
  }

  let count = 0,
    result = [];

  for (let key in map) {
    if (map[key].status) {
      const r = `${key} ${map[key].diff}`;
      result.push(r);
      count++;
    }
  }

  console.log(count);
  console.log(result.join("\n"));
}

;(function () {

	print(function (n) {

		var m = {alphabet: []};
		readline().split(' ').forEach(function (e, i) {
			if (m[e = parseInt(e)]) return m[e].push(i);
			m[e] = [i]; m.alphabet.push(e);
		});

		m.alphabet.map(function (e) { return e; }).forEach(function (e, i) {
			var a = m[e];

			if (a.length === 1) return m[e] = e + ' 0';

			var d = a[1] - a[0], flag = true;
			for (var i = 2, _i = a.length; i < _i; i++) {
				if (a[i] - a[i - 1] !== d) {
					flag = false;
					break;
				}
			}

			if (flag) m[e] = e + ' ' + d;
			else m.alphabet.splice(m.alphabet.indexOf(e), 1);

		});

		if (m.alphabet.length === 0) return 0;

		m.alphabet.sort(function (a, b) { return a - b; });

		return [m.alphabet.length].concat(m.alphabet.map(function (e) { return m[e]; })).join('\n');

	}(+readline()));

}.call(this));

var elem = function(lastpos,isNew,prog){
    this.lastpos=-1;
    this.isNew=isNew;
    this.prog=prog;
}
var n = parseInt(readline());
var a = readline().trim().split(' ').map((x)=>parseInt(x));

var map =[];
var N_MAX = 100006;
for(var i=0;i<N_MAX;i++){
    map.push(new elem(i,true,""));
}
var maxElem= -1;
var nbr = 0;
for(var i in a){
    if(map[a[i]].prog==-1)
        continue;
    maxElem = Math.max(maxElem,a[i]);
    if(map[a[i]].prog===""){
       map[a[i]].lastpos= i;
       map[a[i]].prog = 0;
       map[a[i]].isNew=true;
       nbr++;
    }else{
        if(map[a[i]].isNew){
            map[a[i]].prog = i - map[a[i]].lastpos;
            map[a[i]].lastpos = i;
            map[a[i]].isNew = false;
        }else{
            if(map[a[i]].prog == (i - map[a[i]].lastpos)){
                map[a[i]].lastpos = i;
            }else{
                map[a[i]].prog=-1;
                nbr--;
            }
        }
    }
}

print(nbr)
for(var i=1;i<=maxElem;i++){
   if(map[i].prog>=0 && map[i].prog!==''){
       print(i+" "+map[i].prog);
   }
}

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 n = parseInt(readline()),
		numbers = tokenizeIntegers(readline()),
		occur = {}, unique = [];
	for (var i = 0; i < n; ++i) {
		var x = numbers[i];
		if (occur[x] === undefined) {
			occur[x] = [i];
			unique.push(x);
		} else {
			occur[x].push(i);
		}
	}
	unique.sort(function (a, b) {
		return a-b;
	});
	var parts = [];
	for (var i = 0; i < unique.length; ++i) {
		var where = occur[unique[i]];
		if (where.length == 1) {
			parts.push(unique[i]+' '+0);
		} else {
			var d = where[1]-where[0], okay = true;
			for (var j = 2; okay && j < where.length; ++j) {
				if (where[j]-where[j-1] != d) {
					okay = false;
				}
			}
			if (okay) {
				parts.push(unique[i]+' '+d);
			}
		}
	}
	print(parts.length);
	if (parts.length != 0) {
		print(parts.join('\n'));
	}
}

main();

var n = parseInt(readline());
var a = readline().trim().split(' ').map((x)=>parseInt(x));

var map = {};

for(var i in a){
    if(map[a[i]]==undefined){
       map[a[i]]=[];
    }
    map[a[i]].push(i);
}
var ans = [];
for(var i in map){
    if(map[i].length==1)
        ans.push([i,0]);
    else if(map[i].length==2){
        ans.push([i,(map[i][1]-map[i][0])]);
    }else{
        var pro = map[i][1]-map[i][0];
        var not = false;
        for(var j=1;j<map[i].length;j++){
            if((map[i][1]-map[i][0])!=pro){
                not = true;
            }
        }
        if(!not){
            ans.push([i,pro]);
        }
    }
}

print(ans.length)
ans.sort(function(a,b){
    return a[0]-b[0];
})
for(var i in ans){
    print(ans[i].join(' '));
}

var n = parseInt(readline());
var a = readline().trim().split(' ').map((x)=>parseInt(x));

var map = {};

for(var i in a){
    if(map[a[i]]==undefined){
       map[a[i]]=[];
    }
    map[a[i]].push(i);
}
var ans = [];
for(var i in map){
    if(map[i].length==1)
        ans.push([i,0]);
    else if(map[i].length==2){
        ans.push([i,(map[i][1]-map[i][0])]);
    }else{
        var pro = map[i][1]-map[i][0];
        var not = false;
        for(var j=1;j<map[i].length;j++){
            if((map[i][1]-map[i][0])!=pro){
                not = true;
            }
        }
        if(!not){
            ans.push([i,pro]);
        }
    }
}

print(ans.length)
ans.sort(function(a,b){
    return a[0]-b[0];
})
for(var i in ans){
    print(ans[i]);
}

var n = parseInt(readline());
var a = readline().trim().split(' ').map((x)=>parseInt(x));

var map = {};

for(var i in a){
    if(map[a[i]]==undefined){
       map[a[i]]=[];
    }
    map[a[i]].push(i);
}
var ans = [];
for(var i in map){
    if(map[i].length==1)
        ans.push(i+' 0');
    else if(map[i].length==2){
        ans.push(i+' '+(map[i][1]-map[i][0]));
    }else{
        var pro = map[i][1]-map[i][0];
        var not = false;
        for(var j=1;j<map[i].length;j++){
            if((map[i][1]-map[i][0])!=pro){
                not = true;
            }
        }
        if(!not){
            ans.push(i+' '+pro);
        }
    }
}

print(ans.length)
for(var i in ans){
    print(ans[i]);
}

;(function () {

	print(function (n) {

		var m = {alphabet: []};
		readline().split(' ').forEach(function (e, i) {
			if (m[e = parseInt(e)]) return m[e].push(i);
			m[e] = [i]; m.alphabet.push(e);
		});

		m.alphabet.forEach(function (e, i) {
			var a = m[e];

			if (a.length === 1) {
				return m[e] = e + ' 0';
			}

			var d = a[1] - a[0], flag = true;
			for (var i = 2, _i = a.length - 1; i < _i; i++) {
				if (a[i] - a[i - 1] !== d) {
					flag = false;
					break;
				}
			}

			if (flag) m[e] = e + ' ' + d;
			else m.alphabet.splice(i, 1);

		});

		m.alphabet.sort(function (a, b) { return a - b; });

		return [m.alphabet.length].concat(m.alphabet.map(function (e) { return m[e]; })).join('\n');

	}(+readline()));

}.call(this));


//Input
// var firstLine = "6 3";  var secondLine = "1 3 5 2 5 4";             var thirdLine = "1 1 0 1 0 0";              //R: 16
// var firstLine = "7 3";  var secondLine = "1 3 5 2 5 4 1";           var thirdLine = "1 1 0 1 0 0 1";            //R: 17
// var firstLine = "5 2";  var secondLine = "1 2 3 4 20";              var thirdLine = "0 0 0 1 0";                //R: 24
// var firstLine = "4 2";  var secondLine = "4 5 6 8";                 var thirdLine = "1 0 1 0";                  //R: 18
// var firstLine = "6 3";  var secondLine = "1 3 5 2 1 15";            var thirdLine = "1 1 0 1 0 0";              //R: 22
// var firstLine = "10 5"; var secondLine = "3 5 9 2 5 9 3 8 8 1";     var thirdLine = "0 1 1 1 0 1 0 0 0 0";      //R: 49
// var firstLine = "10 4"; var secondLine = "9 5 6 4 3 9 5 1 10 7";    var thirdLine = "0 0 0 0 0 0 1 0 0 1";      //R: 36
// var firstLine = "10 1"; var secondLine = "6 6 8 7 6 6 3 2 5 6";     var thirdLine = "0 0 1 0 0 1 0 1 1 1";      //R: 34
// var firstLine = "10 5"; var secondLine = "1 1 1 1 1 1 1 1 10000 1"; var thirdLine = "1 1 1 1 1 1 1 1 0 1";      //R: 10009

var firstLine = readline(); var secondLine = readline(); var thirdLine = readline();

retorno = eval(firstLine, secondLine, thirdLine);

//Solution
function eval(firstLine, secondLine, thirdLine){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var n = tmp[0];
    var k = tmp[1];
    var theorems = secondLine.split(" ").map(function(x){ return parseInt(x)});//.map(parseInt);
    var behavior = thirdLine.split(" ").map(function(x){ return parseInt(x)});

    write(calculate(n, k, theorems, behavior));
    // console.log(calculate(n, k, theorems, behavior));
    // return "Hola";
};

function calculate(n, k, theorems, behavior){
    var maxSecretTechnique = 0;
    var secretTechnique = 0;
    var startingIndex = 0;

    for(var i = 0 ; i < (k) ; i++){
        secretTechnique += theorems[i];
    }
    //console.log("secretTechnique: " + secretTechnique);
    for(var i = k ; i < n ; i++){
        secretTechnique += theorems[i]*behavior[i]
    };
    //console.log("secretTechnique: " + secretTechnique + "\n\n");

    maxSecretTechnique = secretTechnique;

    for (var i = 0 ; i < (n-k) ; i++){
        if(behavior[i+k] == 0){
            secretTechnique += (theorems[i+k]);
        };
        if(behavior[i] == 0){
            secretTechnique = secretTechnique - theorems[i];
        };
        //console.log("i:"  + i + "      secretTechnique: " + secretTechnique + "   + theorems[" + (i+k) + "]: "  + theorems[i+k] + ": " + secretTechnique);

        if(maxSecretTechnique < secretTechnique){
            maxSecretTechnique = secretTechnique;
        };

    };

    return maxSecretTechnique;
};

/*
function calculate(n, k, theorems, behavior){
    var maxSecretTechnique = 0;
    var secretTechnique = 0;
    var startingIndex = 0;

    for(var i = 0 ; i <= (n-k) ; i++){
        if(i == 0){
            for(var j = 0 ; j < k ; j++){
            secretTechnique += theorems[i+j];
            };
            for(var j = k ; j < n ; j++){
                secretTechnique += 1//sumar acá el producto de los dos vectores
            };
            console.log(i + ". secretTechnique: " + secretTechnique + "    k: " + k);
        } else{
            console.log(i + ". secretTechnique: " + secretTechnique + "    theorems[" + (i+k-1) + "]: (+" + theorems[i+k-1] + ")    theorems[" + (i-1) + "]: (-" + theorems[i-1] + ")    new value: " + ( secretTechnique + (theorems[i+k-1]) - (theorems[i-1]) ) );
            secretTechnique  = secretTechnique + (theorems[i+k-1]) - (theorems[i-1]);
        };
        // console.log("secretTechnique: " + secretTechnique);

        if(maxSecretTechnique < secretTechnique){
            maxSecretTechnique = secretTechnique;
            startingIndex = i;
        };
    };
    //#endregion

    //#region código en desuso
    // for(var i = 0 ; i <= (n-k) ; i++){
    //     var secretTechnique = 0;
    //     for(var j = 0 ; j < k ; j++){
    //     secretTechnique += theorems[i+j];
    //     };
    //     if(maxSecretTechnique < secretTechnique){
    //         maxSecretTechnique = secretTechnique;
    //         startingIndex = i;
    //     };
    //     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex + "\n");
    // };
    // #endregion

    console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = 0 ; i < startingIndex ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = startingIndex + k ; i < n ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);

    return maxSecretTechnique;
};
*/

// function calculate(n, k, theorems, behavior){
//     var maxSecretTechnique = 0;
//     var startingIndex = 0;
//     for(var i = 0 ; i <= (n-k) ; i++){
//         var secretTechnique = 0;
//         for(var j = 0 ; j < k ; j++){
//         secretTechnique += theorems[i+j];
//         };
//         if(maxSecretTechnique < secretTechnique){
//             maxSecretTechnique = secretTechnique;
//             startingIndex = i;
//         };
//         // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex + "\n");
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
//     for(var i = 0 ; i < startingIndex ; i++){
//         maxSecretTechnique += theorems[i] * behavior[i];
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
//     for(var i = startingIndex + k ; i < n ; i++){
//         maxSecretTechnique += theorems[i] * behavior[i];
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);

//     return maxSecretTechnique;
// };

'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 main() {
  const [n, k] = readline().split(" ").map(x => parseInt(x));
  const a = readline().split(" ").map(x => parseInt(x));
  const t = readline().split(" ").map(x => parseInt(x));
  let awake = t.reduce((acc,curr,index) => acc += a[index]*curr, 0);
  let extra = 0;
  for (let i=0; i<k; i++) {
    extra += (1-t[i]) * a[i];
  }

  let max = extra;
  for (let i=k; i<n; i++) {
    extra += (1-t[i]) * a[i] - (1-t[i-k]) * a[i-k];
    max = Math.max(max, extra);
  }

  console.log(awake+max);
}

var isNodeJS = false;
// isNodeJS = !isNodeJS;
var doWork = (readline, print) => {
var readInts = () => {
    return readline().split(" ").map(function(x) { return parseInt(x); });
};

/////////////////////////////////////////////////////////////// BEGIN

var nums = readInts();
var n = nums[0];
var k = nums[1];

var a = readInts();
var t = readInts();

var always = 0;

t.forEach((_, i) => {
    if (t[i] == 1) {
        always += a[i];
        a[i] = 0;
    }
});

var s = new Array(n).fill(0);

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

var best = 0;
for (var i = 0; i < n; ++i) {
    var current = always + s[i] - (i - k >= 0 ? s[i - k] : 0);
    if (best < current) best = current;
}

print(best + "\n");

/////////////////////////////////////////////////////////////// END OF CODE
};

if (isNodeJS) {
    var stdin = process.stdin;
    var stdout = process.stdout;
    var lines, currentLine = 0;
    stdin.resume();
    stdin.once('data', function(data) {
        data = data.toString().trim();
        lines = data.split("\n");
        var readline = () => {
            return lines[currentLine++];
        };
        doWork(readline, stdout.write.bind(stdout));
    });
} else {
    doWork(readline, print);
}

//Input
// var firstLine = "6 3"; var secondLine = "1 3 5 2 5 4"; var thirdLine = "1 1 0 1 0 0";
// var firstLine = "7 3"; var secondLine = "1 3 5 2 5 4 1"; var thirdLine = "1 1 0 1 0 0 1";

var firstLine = readline(); var secondLine = readline(); var thirdLine = readline();

retorno = eval(firstLine, secondLine, thirdLine);

//Solution
function eval(firstLine, secondLine, thirdLine){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var n = tmp[0];
    var k = tmp[1];
    var theorems = secondLine.split(" ").map(function(x){ return parseInt(x)});//.map(parseInt);
    var behavior = thirdLine.split(" ").map(function(x){ return parseInt(x)});

    write(calculate(n, k, theorems, behavior));
    // console.log(calculate(n, k, theorems, behavior));
    // return "Hola";
};

function calculate(n, k, theorems, behavior){
    var maxSecretTechnique = 0;
    var secretTechnique = 0;
    var startingIndex = 0;

    for(var i = 0 ; i <= (n-k) ; i++){
        if(i == 0){
            for(var j = 0 ; j < k ; j++){
            secretTechnique += theorems[i+j];
            };
            //console.log("secretTechnique: " + secretTechnique);
        } else{
            //console.log("secretTechnique: " + secretTechnique + "    theorems[" + (i+k-1) + "]: + " + theorems[i+k-1] + "    theorems[" + (i-1) + "]: - " + theorems[i-1] + "new value: " + ( secretTechnique + (theorems[i+k-1]) - (theorems[i-1]) ) );
            secretTechnique  = secretTechnique + (theorems[i+k-1]) - (theorems[i-1]);
        };
        //console.log("secretTechnique: " + secretTechnique);

        if(maxSecretTechnique < secretTechnique){
            maxSecretTechnique = secretTechnique;
            startingIndex = i;
        };
    };

    //#region código en desuso
    // for(var i = 0 ; i <= (n-k) ; i++){
    //     var secretTechnique = 0;
    //     for(var j = 0 ; j < k ; j++){
    //     secretTechnique += theorems[i+j];
    //     };
    //     if(maxSecretTechnique < secretTechnique){
    //         maxSecretTechnique = secretTechnique;
    //         startingIndex = i;
    //     };
    //     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex + "\n");
    // };
    // #endregion

    // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = 0 ; i < startingIndex ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = startingIndex + k ; i < n ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);

    return maxSecretTechnique;
};

// function calculate(n, k, theorems, behavior){
//     var maxSecretTechnique = 0;
//     var startingIndex = 0;
//     for(var i = 0 ; i <= (n-k) ; i++){
//         var secretTechnique = 0;
//         for(var j = 0 ; j < k ; j++){
//         secretTechnique += theorems[i+j];
//         };
//         if(maxSecretTechnique < secretTechnique){
//             maxSecretTechnique = secretTechnique;
//             startingIndex = i;
//         };
//         // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex + "\n");
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
//     for(var i = 0 ; i < startingIndex ; i++){
//         maxSecretTechnique += theorems[i] * behavior[i];
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
//     for(var i = startingIndex + k ; i < n ; i++){
//         maxSecretTechnique += theorems[i] * behavior[i];
//     };
//     // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);

//     return maxSecretTechnique;
// };

//Input
// var firstLine = "6 3"; var secondLine = "1 3 5 2 5 4"; var thirdLine = "1 1 0 1 0 0";
// var firstLine = "7 3"; var secondLine = "1 3 5 2 5 4 1"; var thirdLine = "1 1 0 1 0 0 1";

var firstLine = readline(); var secondLine = readline(); var thirdLine = readline();

retorno = eval(firstLine, secondLine, thirdLine);

//Solution
function eval(firstLine, secondLine, thirdLine){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var n = tmp[0];
    var k = tmp[1];
    var theorems = secondLine.split(" ").map(function(x){ return parseInt(x)});//.map(parseInt);
    var behavior = thirdLine.split(" ").map(function(x){ return parseInt(x)});

    write(calculate(n, k, theorems, behavior));
    // console.log(calculate(n, k, theorems, behavior));
    // return "Hola";
};

function calculate(n, k, theorems, behavior){
    var maxSecretTechnique = 0;
    var startingIndex = 0;
    for(var i = 0 ; i <= (n-k) ; i++){
        var secretTechnique = 0;
        if(behavior[i] == 0){
            for(var j = 0 ; j < k ; j++){
            secretTechnique += theorems[i+j];
            // console.log("n: " + i + "    k: " + j + "    i+k: " + (i+j) + "    secretTechnique: " + secretTechnique);
            };
            // console.log("secretTechnique: " + secretTechnique);
            if(maxSecretTechnique < secretTechnique){
                maxSecretTechnique = secretTechnique;
                startingIndex = i;
            };
            // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
            // console.log("\n");
        };
    };
    // console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = 0 ; i < startingIndex ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    //console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);
    for(var i = startingIndex + k ; i < n ; i++){
        maxSecretTechnique += theorems[i] * behavior[i];
    };
    //console.log("maxSecretTechnique: " + maxSecretTechnique + "    startingIndex: " + startingIndex);

    return maxSecretTechnique;
};


var data = readline().split(' '),
    m = parseInt(data[0]),
    n = parseInt(data[1]);

var b = 0,
    Xmin = -1,
    Ymin = -1,
    Xmax = -1,
    Ymax = -1;

for(var i = 0; i < m; i++) {
    var line = readline();

    for(var j = 0; j < n; j++) {
        if(line.charAt(j) === 'B') {
            if(b === 0) {
                Xmin = i;
                Ymin = j;
                Xmax = i;
                Ymax = j;
            } else {
                if(Xmin > i) {
                    Xmin = i;
                }
                if(Ymin > j) {
                    Ymin = j;
                }
                if(Xmax < i) {
                    Xmax = i;
                }
                if(Ymax < j) {
                    Ymax = j;
                }
            }
            b++;
        }
    }
}

if(b === 0) {
    print(1);
} else if(b === 1){
    print(0);
} else if(b === m * n && m === n) {
    print(0);
} else if (b === m * n && m !== n) {
    print(-1);
} else if(m === 1 || n === 1) {
    print(-1);
} else {
    var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));
    if(a > n || a > m) {
        print(-1);
    } else {
        var s = a * a;
        var output = s - b;
        print(output);
    }

}

var s = readline().split(' ').map(Number);
var n = s[0], m = s[1];

var leftExt = null, rightExt = null, topExt = null, bottomExt = null;
var blacksCount = 0;

for (var i = 0; i < n; i++) {
  var currString = readline();
  var count = 0;

  for (var j = 0; j < m; j++) {
    if (currString[j] === 'B') {
      blacksCount += 1;
      count++;

      if (leftExt === null) {
        leftExt = j;
      } else if (j < leftExt) {
        leftExt = j;
      }

      if (rightExt === null) {
        rightExt = j;
      } else if (j > rightExt) {
        rightExt = j;
      }
    }
  }

  if (count > 0) {
  	if (topExt === null) {
            topExt = i;
          } else if (i < topExt) {
            topExt = i;
          }

          if (bottomExt === null) {
            bottomExt = i;
          } else if (i > bottomExt) {
            bottomExt = i;
          }
    }
}

var verticalSideLength = bottomExt - topExt + 1;
var horizontalSideLength = rightExt - leftExt + 1;
var maxSideLength = Math.max(horizontalSideLength, verticalSideLength);

if (maxSideLength > n || maxSideLength > m) {
    print('-1');
} else {
    print(maxSideLength * maxSideLength - blacksCount);
};

var s = readline().split(' ').map(Number);
var n  = s[0], m = s[1];
var white = 0, black = 0, res, r, d, l, u;

var arr = [];
for (var i = 0; i < n; i++) {
    var s1 = readline();
    arr.push(s1);
    for (var j = 0; j < m; j++) {
        if (s1[j] === 'B') {
            u = u !== undefined ? Math.min(u, i) : i;
            d = d !== undefined ? Math.max(d, i) : i;
            l = l !== undefined ? Math.min(l, j) : j;
            r = r !== undefined ? Math.max(r, j) : j;
            black++;
        }
    }
}
if (black === 0) {
    print(1);
}
else {
    var sqSide = Math.max(r-l+1, d-u+1);
    var recSide = Math.min(r-l+1, d-u+1);
    if (sqSide > n || sqSide > m) {
        print(-1);
    }
    else {
        for (var i = u; i<=d; i++) {
            for (var j = l; j<=r; j++) {
                if (arr[i][j] === 'W') {
                    white++;
                }
            }
        }
        res = white + (sqSide - recSide) * sqSide;
        print(res);
    }
}

var data = readline().split(' '),
    m = parseInt(data[0]),
    n = parseInt(data[1]);

var b = 0,
    Xmin = -1,
    Ymin = -1,
    Xmax = -1,
    Ymax = -1;

for(var i = 0; i < m; i++) {
    var line = readline();

    for(var j = 0; j < n; j++) {
        if(line.charAt(j) === 'B') {
            if(b === 0) {
                Xmin = i;
                Ymin = j;
                Xmax = i;
                Ymax = j;
            } else {
                if(Xmin > i) {
                    Xmin = i;
                }
                if(Ymin > j) {
                    Ymin = j;
                }
                if(Xmax < i) {
                    Xmax = i;
                }
                if(Ymax < j) {
                    Ymax = j;
                }
            }
            b++;
        }
    }
}

if(b === 0) {
    print(1);
} else if(b === 1){
    print(0);
} else if(b === m * n) {
    print(0);
} else if(m === 1 || n === 1) {
    print(-1);
} else {
    var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));
    if(a > n || a > m) {
        print(-1);
    } else {
        var s = a * a;
        var output = s - b;
        print(output);
    }

}

var data = readline().split(' '),
    m = parseInt(data[0]),
    n = parseInt(data[1]);

var b = 0,
    Xmin = -1,
    Ymin = -1,
    Xmax = -1,
    Ymax = -1;

for(var i = 0; i < m; i++) {
    var line = readline();

    for(var j = 0; j < n; j++) {
        if(line.charAt(j) === 'B') {
            if(b === 0) {
                Xmin = i;
                Ymin = j;
                Xmax = i;
                Ymax = j;
            } else {
                if(Xmin > i) {
                    Xmin = i;
                }
                if(Ymin > j) {
                    Ymin = j;
                }
                if(Xmax < i) {
                    Xmax = i;
                }
                if(Ymax < j) {
                    Ymax = j;
                }
            }
            b++;
        }
    }
}

if(b === 0) {
    print(1);
} else if(b === 1){
    print(0);
} else if(b === m * n) {
    print(-1);
} else if(m === 1 || n === 1) {
    print(-1);
} else {
    var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));
    if(a > n || a > m) {
        print(-1);
    } else {
        var s = a * a;
        var output = s - b;
        print(output);
    }

}

var data = readline().split(' '),
    m = data[0],
    n = data[1];

var b = 0,
    Xmin = -1,
    Ymin = -1,
    Xmax = -1,
    Ymax = -1;

for(var i = 0; i < m; i++) {
    var line = readline();

    for(var j = 0; j < n; j++) {
        if(line.charAt(j) === 'B') {
            if(b === 0) {
                Xmin = i;
                Ymin = j;
                Xmax = i;
                Ymax = j;
            } else {
                if(Xmin > i) {
                    Xmin = i;
                }
                if(Ymin > j) {
                    Ymin = j;
                }
                if(Xmax < i) {
                    Xmax = i;
                }
                if(Ymax < j) {
                    Ymax = j;
                }
            }
            b++;
        }
    }
}

if(b === 0) {
    print(1);
} else if(b === 1){
    print(0);
} else if(b === m * n) {
    print(-1);
} else {
    var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));
    var s = a * a;
    var output = s - b;
    print(output);
}

var data = readline().split(' '),
    m = parseInt(data[0]),
    n = parseInt(data[1]);

var b = 0,
    Xmin = -1,
    Ymin = -1,
    Xmax = -1,
    Ymax = -1;

for(var i = 0; i < m; i++) {
    var line = readline();

    for(var j = 0; j < n; j++) {
        if(line.charAt(j) === 'B') {
            if(b === 0) {
                Xmin = i;
                Ymin = j;
                Xmax = i;
                Ymax = j;
            } else {
                if(Xmin > i) {
                    Xmin = i;
                }
                if(Ymin > j) {
                    Ymin = j;
                }
                if(Xmax < i) {
                    Xmax = i;
                }
                if(Ymax < j) {
                    Ymax = j;
                }
            }
            b++;
        }
    }
}

if(b === 0) {
    print(1);
} else if(b === 1){
    print(0);
} else if(b === m * n) {
    print(-1);
} else if(m === 1 || n === 1) {
    print(-1);
} else {
    var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));
    var s = a * a;
    var output = s - b;
    print(output);
}

var s = readline().split(' ').map(Number);
var n = s[0], m = s[1];

var leftExt = null, rightExt = null, topExt = null, bottomExt = null;
var blacksCount = 0;

for (var i = 0; i < n; i++) {
  var currString = readline();

  for (var j = 0; j < m; j++) {
    if (currString[j] === 'B') {
      blacksCount += 1;

      if (leftExt === null) {
        leftExt = j;
      } else if (j < leftExt) {
        leftExt = j;
      }

      if (rightExt === null) {
        rightExt = j;
      } else if (j > rightExt) {
        rightExt = j;
      }
    }
  }

  if (topExt === null) {
    topExt = i;
  } else if (i < topExt) {
    topExt = i;
  }

  if (bottomExt === null) {
    bottomExt = i;
  } else if (i > bottomExt) {
    bottomExt = i;
  }
}

var horizontalSideLength = bottomExt - topExt + 1;
var verticalSideLength = rightExt - leftExt + 1;
var maxSideLength = Math.max(horizontalSideLength, verticalSideLength);

print(bottomExt);
print(topExt);

if (bottomExt + 1 - maxSideLength < 0) {
  print("-1");
} else if (rightExt + 1 - maxSideLength < 0) {
  print("-1");
} else {
    print(maxSideLength * maxSideLength - blacksCount);
}

var s = readline().split(' ').map(Number);
var n = s[0], m = s[1];

var leftExt = null, rightExt = null, topExt = null, bottomExt = null;
var blacksCount = 0;

for (var i = 0; i < n; i++) {
  var currString = readline();
  var count = 0;

  for (var j = 0; j < m; j++) {
    if (currString[j] === 'B') {
      blacksCount += 1;
      count++;

      if (leftExt === null) {
        leftExt = j;
      } else if (j < leftExt) {
        leftExt = j;
      }

      if (rightExt === null) {
        rightExt = j;
      } else if (j > rightExt) {
        rightExt = j;
      }
    }
  }

  if (count > 0) {
  	if (topExt === null) {
            topExt = i;
          } else if (i < topExt) {
            topExt = i;
          }

          if (bottomExt === null) {
            bottomExt = i;
          } else if (i > bottomExt) {
            bottomExt = i;
          }
    }
}

var verticalSideLength = bottomExt - topExt + 1;
var horizontalSideLength = rightExt - leftExt + 1;
var maxSideLength = Math.max(horizontalSideLength, verticalSideLength);

if (bottomExt + 1 - maxSideLength < 0) {
  print("-1");
} else if (rightExt + 1 - maxSideLength < 0) {
  print("-1");
} else {
    print(maxSideLength * maxSideLength - blacksCount);
}