zoukankan      html  css  js  c++  java
  • poj 1256 Anagram(dfs)

    题目链接:http://poj.org/problem?id=1256

    思路分析:该题为含有重复元素的全排列问题;由于题目中字符长度较小,采用暴力法解决。

    代码如下:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    const int MAX_N = 20;
    char P[MAX_N], A[MAX_N];
    
    char * SortAlp(char P[], int n)
    {
        int Low[MAX_N], Upper[MAX_N];
        int LowLen, UpperLen;
    
        LowLen = UpperLen = 0;
        for (int i = 0; i < n; ++ i)
        {
            if ('A' <= P[i] && P[i] <= 'Z')
                Upper[UpperLen++] = P[i];
            else
                Low[LowLen++] = P[i];
        }
        sort(Low, Low + LowLen);
        sort(Upper, Upper + UpperLen);
    
        int Index_L, Index_U;
        Index_L = Index_U = 0;
        for (int j = 0; j < n; ++j)
        {
            if (Upper[Index_U] - 'A' + 'a' <= Low[Index_L]
                && Index_U < UpperLen)
                P[j] = Upper[Index_U++];
            else
                P[j] = Low[Index_L++];
        }
        return P;
    }
    
    void PrintPermutation(int n, char P[], char A[], int cur)
    {
        int i, j;
    
        if (cur == n)
        {
            for (i = 0; i < n; ++i)
                printf("%c", A[i]);
            printf("
    ");
        }
        else
        {
            for (i = 0; i < n; ++i)
            {
                if (!i || P[i] != P[i-1])
                {
                    int c1 = 0, c2 = 0;
    
                    for (j = 0; j < cur; ++j)
                        if (A[j] == P[i]) c1++;
                    for (j = 0; j < n; ++j)
                        if (P[i] == P[j]) c2++;
    
                    if (c1 < c2)
                    {
                        A[cur] = P[i];
                        PrintPermutation(n, P, A, cur + 1);
                    }
                }
            }
        }
    }
    
    int main()
    {
        int n;
        char P[MAX_N];
    
        cin >> n;
        for (int i = 0; i < n; ++i)
        {
            cin >> P;
            SortAlp(P, strlen(P));
            PrintPermutation(strlen(P), P, A, 0);
        }
        return 0;
    }
  • 相关阅读:
    ndk与jni学习
    2021杭电多校第十场题解
    2021杭电多校第九场题解
    2021杭电多校第八场题解
    2021杭电多校第七场题解
    2021杭电多校第六场题解
    2021杭电多校第四场题解
    2021杭电多校第五场题解
    2021杭电多校第三场题解
    2021杭电多校第二场题解
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4020017.html
Copyright © 2011-2022 走看看