UVa140 Bandwidth

本文深入探讨了在给定字符串集合中查找特定字符序列的算法,通过实现DFS深度优先搜索,优化路径选择,解决字符串匹配问题,并提供详细步骤和代码实现,旨在提升编程技能和理解复杂数据结构的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#define MAXN 30
#define BUFLEN 80
#define STRLEN 30

int graph[MAXN][MAXN];
int hasChar[STRLEN];
int Char[STRLEN];
int len;
int vis[STRLEN];
int max;
int result[STRLEN];
int ans[STRLEN];

int cmp_char(const void *a, const void *b);
void dfs(int cur);

int main()
{
    int i;
    char buf[BUFLEN];
    int start, end;

    #ifndef ONLINE_JUDGE
        freopen("d:\\uva_in.txt", "r", stdin);
    #endif

    while (scanf("%s", buf) && buf[0] != '#') {
        memset(hasChar, -1, sizeof(hasChar));
        memset(graph, 0, sizeof(graph));
        memset(vis, 0, sizeof(vis));
        max = 100;

        i = 0;
        len = 0;
        while (i < strlen(buf)) {


            start = buf[i] - 'A';
            if (hasChar[start] == -1) {
                hasChar[start] = 1;
                Char[len++] = start;
            }


            i += 2;

            while (isalpha(buf[i])) {
                end = buf[i] - 'A';
                if (hasChar[end] == -1) {
                    hasChar[end] = 1;
                    Char[len++] = end;
                }
                graph[start][end] = graph[end][start] = 1;
                i++;
            }
            i++;
        }


        qsort(Char, len, sizeof(int), cmp_char);

        dfs(0);

        for (i = 0; i < len; i++) {
            printf("%c ", ans[i] + 'A');
        }
        printf("-> %d\n", max);

    }

    return 0;
}

int cmp_char(const void *a, const void *b)
{
    const int *tmp_a = (const int *)a;
    const int *tmp_b = (const int *)b;

    return *tmp_a - *tmp_b;
}


void dfs(int cur)
{
    int i, j;
    int temp;

    if (cur == len) {
        temp = 0;
        for (i = 0; i < cur - 1; i++) {
            for (j = i + 1; j < cur; j++) {
                if (graph[result[i]][result[j]] && (j - i) > temp)
                    temp = j - i;
            }
        }

        if (temp < max) {
            max = temp;
            memcpy(ans, result, sizeof(result));
        }
    } else {
        for (i = 0; i < len; i++) {
            if (!vis[i]) {
                vis[i] = 1;
                result[cur] = Char[i];
                dfs(cur + 1);
                vis[i] = 0;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值