You are given a string str. It costs one unit of a coin to change a character at an index. Your task is to convert it into a palindrome with minimum coins. Also, you are given number of queries. The queries are of the following types:
- 1 A B
- 2
After solving the first type of query, you can convert character into character without any cost and vice versa. In the second type of query, you are required to answer the minimum cost that is required to convert the given string into a palindrome.
Note: If character can be converted to character and character can be converted to character , then you can convert character to character .
Example:
Input:10 vwuhjdbgzp 4 1 a b 2 1 w z 2Output:54
Approach
Java
public class TwoTypesQueries {private static int[] parent;public static void main(String args[]) {int n = 10;String s = "vwuhjdbgzp";int[][] differentChars = new int[26][26];int count = 0;for (int i = 0; i < n / 2; i++) {int a = s.charAt(i) - 'a';int b = s.charAt(n - 1 - i) - 'a';if (a != b) {differentChars[a][b]++;differentChars[b][a]++;count++;}}// initilized graphinitializeGraph(26);boolean isCalculated = true;int q = 4;StringBuffer sb = new StringBuffer();char[][] arr = { { 1, 'a', 'b' }, { 2 }, { 1, 'w', 'z' }, { 2 } };for (int k = 0; k < q; k++) {int cmd = arr[k][0];switch (cmd) {case 1:int a = arr[k][1] - 'a';int b = arr[k][2] - 'a';if (a != b)addEdge(a, b);isCalculated = false;break;case 2:if (!isCalculated) {for (int i = 0; i < 26; i++) {for (int j = i + 1; j < 26; j++) {if (differentChars[i][j] > 0) {int x = getRoot(i);int y = getRoot(j);if (x == y) {count -= differentChars[i][j];differentChars[i][j] = 0;differentChars[j][i] = 0;}}}}isCalculated = true;}sb.append(count).append("\n");break;}}System.out.print(sb);}private static void initializeGraph(int n) {parent = new int[n];for (int i = 0; i < n; i++) {parent[i] = i;}}private static void addEdge(int a, int b) {int x = getRoot(a);int y = getRoot(b);if (x != y) {if (x < y) {parent[y] = x;} else {parent[x] = y;}}}private static int getRoot(int node) {int p = parent[node];if (node != p && p != parent[p]) {parent[node] = getRoot(p);}return parent[node];}}
No comments:
Post a Comment