分治问题POJ1854_构造回文
来源:互联网 发布:大连淘宝代运营 编辑:程序博客网 时间:2024/05/22 05:11
题目
A palindrome is a string of symbols that is equal to itself when reversed. Given an input string, not necessarily a palindrome, compute the number of swaps necessary to transform the string into a palindrome. By swap we mean reversing the order of two adjacent symbols. For example, the string “mamad” may be transformed into the palindrome “madam” with 3 swaps:
swap “ad” to yield “mamda”
swap “md” to yield “madma”
swap “ma” to yield “madam”
Input
The first line of input gives n, the number of test cases. For each test case, one line of input follows, containing a string of up to 8000 lowercase letters.
Output
Output consists of one line per test case. This line will contain the number of swaps, or “Impossible” if it is not possible to transform the input to a palindrome.
Sample Input
3
mamad
asflkj
aabb
Sample Output
3
Impossible
2
import java.util.ArrayList;import java.util.Scanner;/** * Created by 95112 on 10/20/2017. */public class POJA { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); ArrayList<String> answers = new ArrayList<>(); for (int i = 0 ; i< n; i++) { String input = scanner.next(); int[] alphabet = new int[26]; for (int j = 0; j < 26 ; j++) alphabet[j] = 0; for (char tmp: input.toCharArray()){ alphabet[tmp - 'a']++; } int count = 0; for (int tmp : alphabet) if (tmp%2 == 1) count++; if (count > 1) { answers.add("Impossible"); continue; } char[] inputChar = input.toCharArray(); int x = 0; int y = input.length()-1; int answer = 0; for ( ; x < input.length() && x < y ; x++,y--){ int left = x; int right = y; for (;left < y; left++){ if (inputChar[left] == inputChar[y]) break; } for (; right > x ; right--){ if (inputChar[right] == inputChar[x]) break; } if (left - x > (y - right)) { char deal; answer += (y - right); for (int start = right ; start < y; start++ ) { deal = inputChar[start+1]; inputChar[start+1] = inputChar[start]; inputChar[start] = deal; } } else { char deal; answer += (left-x); for (int start = left; start > 0 ; start--) { deal = inputChar[start]; inputChar[start] = inputChar[start-1]; inputChar[start-1] = deal; } } } answers.add(String.valueOf(answer)); } for (String answer : answers) System.out.println(answer); }}
- 分治问题POJ1854_构造回文
- 最长公共字串算法-构造回文问题
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 构造回文
- 回文质数 构造回文数
- 腾讯 构造回文
- 构造回文字符串
- 牛客网-构造回文字符串
- PAT乙级1004 成绩排名
- c# 调用打印机
- BZOJ 1051 受欢迎的牛
- 二进制安装mariadb
- 2017年10月18日普及组 面积最大
- 分治问题POJ1854_构造回文
- LINUX 如何开放端口和关闭端口
- 深度学习资料
- 同步网络传输和异步网络传输
- 实验3
- Docker镜像制作
- codevs 1904 最小路径覆盖问题
- python安装过程及问题图解
- 记:破解MFC小程序02