zoukankan      html  css  js  c++  java
  • UVA 10716 Evil Straw Warts Live(贪心)

    Problem D: Evil Straw Warts Live

    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"

    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 100 lowercase letters. 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
    

    Output for Sample Input

    3
    Impossible
    2

    题意:给定一些字符串,要求出能否通过交换字母变换为回文。。如果可以输出最少变换次数。。

    思路:贪心。。

    1、先判断能不能变换为回文。。如果字符串中没有或只有1个字母是奇数。就可以组成。。

    2、每次从第一个字母开始。从后往前找到一个相同字母。放到最后就是匹配了。。每次移动的次数为当前位置到最后的位置的距离。

    要注意有单个字母为奇数的情况。。最后要把这个字母另外拿出来移到最中间。。一开始没考虑这个wa了- -

    代码:

    #include <stdio.h>
    #include <string.h>
    
    int t, len, sum, judge, end, vis[30], mark[105];
    char sb[105], v;
    
    void Init() {
        sum = 0;
        judge = 1;
        memset(vis, 0, sizeof(vis));
        memset(mark, 0, sizeof(mark));
        gets(sb);
        len = strlen(sb);
        end = len - 1;
    }
    
    void Judge() {//判断能不能组成回文
        int bo = 0;
        for (int i = 0; i < len; i ++)
    	vis[sb[i] - 'a'] ++;
        for (int i = 0; i < 26; i ++) {
    	if (vis[i] % 2) {
    	    bo ++;
    	    if (bo == 2) {
    		judge = 0;
    		break;
    	    }
    	    v = i + 'a';
    	}
        }
    }
    
    void solve() {//变换
        for (int i = 0; i < len / 2; i ++) {
    	int j;
    	for (j = end; j >= i + 1; j --)
    	    if (sb[j] == sb[i]) {
    		mark[i] = 1;
    		sum += end - j;
    		for (int k = j; k < end; k ++)
    		    sb[k] = sb[k + 1];
    		end --;
    		break;
    	    }
        }
        if (len % 2) {//奇数情况
    	for (int i = 0; i < len; i ++)
    	   if (sb[i] == v && mark[i] == 0) {
    	       sum += len / 2 - i;
    	       break;
    	   } 
        }
        if (judge)
    	printf("%d
    ", sum);
        else
    	printf("Impossible
    ");
    }
    int main() {
        scanf("%d%*c", &t);
        while (t --) {
    	Init();
    	Judge();
    	solve();
        }
        return 0;
    }


  • 相关阅读:
    Vue 应用 nginx 配置 前后端不分离模式
    解决使用antd Modal组件时数据污染问题
    关于antd怎么在父组件中控制子组件的表单提交
    Web前端工程师面试题1-1
    Web前端工程师面试题7-4
    react 的 生命周期
    字符串的方法
    栈的基本算法
    node.js 获取文件目录
    bat脚本文件启动UG NX软件,动态调用外挂,以及设置环境变量
  • 原文地址:https://www.cnblogs.com/james1207/p/3268723.html
Copyright © 2011-2022 走看看