2013年2月10日 星期日

ACM 10098 Generating Fast

做法是看DJWS大大的演算法筆記
所以不做說明了
CODE如下

#include <stdio.h>
#include <string.h>

char s[10+1], ans[10];
int len, used[10];

void bubble_sort(char *str, int n)
{
    int i, j;
    char temp;

    for (i = n-1; i >= 1; --i)
        for (j = 0; j < i; ++j)
            if (str[j] > str[j+1]) {
                temp = str[j];
                str[j] = str[j+1];
                str[j+1] = temp;
            }
}

void permutation(int depth)
{
    int i;
    char last_letter;

    if (depth == len) {
        for (i = 0; i < len; ++i)
            putchar(ans[i]);
        putchar('\n');
        return;
    }

    last_letter = '\0';
    for (i = 0; i < len; ++i)
        if (!used[i] && s[i] != last_letter) {
            used[i] = 1;
            ans[depth] = s[i];
            permutation(depth+1);
            used[i] = 0;
            last_letter = s[i];
        }
}

int main(void)
{
    int i, n;

    scanf("%d", &n);
    getchar();

    while (n--) {
        gets(s);
        len = strlen(s);

        bubble_sort(s, len);

        for (i = 0; i < len; ++i)
            used[i] = 0;
        permutation(0);
        putchar('\n');
    }

    return 0;
}

沒有留言:

張貼留言