ACM – 5.3 排序檢索

svtter發表於2019-05-13

5.3.1 6174問題

主要涉及了字串的翻轉

c#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>

using namespace std;

int get_next(int x)
{
    char num[5];
    sprintf(num, "%d", x);
    int len = strlen(num);
    // buble sort
    for(int i = 0; i < len; i++)
    {
        for(int j = i+1; j < len; j++)
        {
            if(num[i] > num[j])
                swap(num[i], num[j]);
        }
    }


    int b;
    sscanf(num, "%d", &b);
    for(int i = 0; i < len/2 ;i ++)
    {
        char t = num[i];
        num[i] = num[len-1-i];
        num[len-1-i] = t;
    }
    sscanf(num, "%d", &x);

    return x - b;
}


int main(int argc, const char *argv[])
{
    int num[2000], count;
    scanf("%d", &num[0]);
    count = 1;
    while(1)
    {
        bool find = false;
        int next = get_next(num[count - 1]);
        for(int i = 0; i < count; i++)
            if(next == num[i])
            {
                find = 1;
                break;
            }

        if(find) {
            for(int i = 0; i < count; i++)
                printf("%d->", num[i]);
            printf("%d
", next);
            break;
        }

        num[count++] = next;
    }
    return 0;
}

5.3.2 字母重排

主要涉及到qsort的使用

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

const int maxl = 10;
const int maxn = 200;

int cmp_char(const void * _a, const void * _b)
{
    char * a = (char*) _a;
    char * b = (char*) _b;
    return *a - *b;
}

int cmp_string(const void *_a, const void *_b)
{
    char * a = (char*) _a;
    char * b = (char*) _b;
    return strcmp(a, b);
}

char word[maxn][maxl];
char sorted[maxn][maxl];

int main()
{
    freopen("input", "r", stdin);
    int n = 0;
    while(1)
    {
        scanf("%s", word[n]);
        if(word[n][0] == `*`) break;
        n++;
    }
    // 陣列名,陣列大小,單位大小,比較函式
    qsort(word, n, sizeof(word[0]), cmp_string);

    for(int i = 0; i < n; i++)
    {
        strcpy(sorted[i], word[i]);
        qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmp_char);
    }

    char t[10];

    while(~scanf("%s", t))
    {
        qsort(t, strlen(t), sizeof(char), cmp_char);
        int found = 0;
        for(int i = 0; i < n; i++)
        {
            if(strcmp(t, sorted[i]) == 0)
            {
                found = 1;
                printf("%s ", word[i]);
            }
        }

        if(!found) printf(":(");
        printf("
");
    }


    return 0;
}

相關文章