Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*
- import java.util.*
- import java.lang.Math.*
- class C {
- fun solve(io: FastIO) {
- val s = io.nextWord()
- val n = s.length
- val d = Array(n, { IntArray(n, { 1e9.toInt() }) })
- val p = Array(n, { IntArray(n, { -1 }) })
- for (i in 1 until n) {
- d[i][i - 1] = 0
- }
- for (i in 0 until n) {
- d[i][i] = 1
- }
- val pp = CharArray(333)
- pp['('.toInt()] = ')'
- pp['['.toInt()] = ']'
- pp['{'.toInt()] = '}'
- for (len in 2..n) {
- for (i in 0..n - len) {
- val j = i + len - 1
- d[i][j] = d[i + 1][j] + 1
- if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
- for (k in i+1..j) {
- if (pp[s[i].toInt()] == s[k]) {
- var c = d[i + 1][k - 1]
- if (k < j) {
- c += d[k + 1][j]
- }
- if (d[i][j] > c) {
- d[i][j] = c
- p[i][j] = k
- }
- }
- }
- }
- }
- }
- fun genAns(i: Int, j: Int) {
- if (i > j) {
- return
- }
- if (p[i][j] == -1) {
- genAns(i + 1, j)
- } else {
- val k = p[i][j]
- io.print(s[i])
- genAns(i + 1, k - 1)
- io.print(s[k])
- genAns(k + 1, j)
- }
- }
- genAns(0, n - 1)
- }
- fun main(args: Array<String>) {
- FastIO(System.`in`, System.out).use {
- solve(it)
- }
- }
- class FastIO(inp: InputStream, out: OutputStream) : PrintWriter(out) {
- private val reader = BufferedReader(InputStreamReader(inp))
- private var tokenizer = StringTokenizer("")
- fun nextToken(): String? {
- while (!tokenizer.hasMoreTokens()) {
- val s = reader.readLine() ?: return null
- tokenizer = StringTokenizer(s)
- }
- return tokenizer.nextToken()
- }
- fun nextInt() = nextToken()!!.toInt()
- fun nextLong() = nextToken()!!.toLong()
- fun nextDouble() = nextToken()!!.toDouble()
- fun nextWord() = nextToken()!!
- fun nextLine() = reader.readLine()
- }
- fun run() {
- FastIO(System.`in`, System.out).use {
- solve(it)
- }
- }
- }
- fun main(args: Array<String>) {
- C().run()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement