一本通1504:【例 1】Word Rings

#include <bits/stdc++.h>
using namespace std;
inline int read() {
    int s = 0, f = 1;
    char a = getchar();

    while (a > '9' || a < '0') {
        if (a == '-')
            f = -1;

        a = getchar();
    }

    while (a >= '0' && a <= '9') {
        s = (s << 1) + (s << 3) + (a ^ 48);
        a = getchar();
    }

    return s * f;
}
#define il inline
const int maxm = 1e5 + 10, maxn = 1000;
const double eps = 1e-6;
struct uzi {
    int to, next, w;
} edge[maxm];
int head[maxn], tot = 0;
il void add(int x, int y, int w) {
    edge[++tot] = {y, head[x], w};
    head[x] = tot;
}
il int cal(char a, char b) {
    return (a - 'a') * 31 + (b - 'a') + 1;
}
bool vis[maxn];
double dis[maxn];
bool spfa(int v, double mid) {
    vis[v] = true;

    for (int i = head[v]; i; i = edge[i].next) {
        int y = edge[i].to;

        if (dis[v] + edge[i].w - mid > dis[y]) {
            dis[y] = dis[v] + edge[i].w - mid;

            if (vis[y] || spfa(y, mid)) {
                vis[y] = false;
                return true;
            }
        }
    }

    vis[v] = false;
    return false;
}
bool check(double mid) {
    memset(dis, 0, sizeof(dis));

    for (int i = 1; i <= 31 * 31; i++)
        if (spfa(i, mid))
            return true;

    return false;
}
char st[1005];
int n;
int main() {
    while (cin >> n && n) {
        memset(head, 0, sizeof(head));
        tot = 0;

        for (int i = 1; i <= n; i++) {
            scanf("%s", st + 1);
            int len = strlen(st + 1);
            add(cal(st[1], st[2]), cal(st[len - 1], st[len]), len);
        }

        double l = 0, r = 1005;

        while (r - l > eps) {
            double mid = (l + r) / 2;

            if (check(mid))
                l = mid;
            else
                r = mid;
        }

        if (l == 0)
            puts("No solution");
        else
            printf("%.3lf\n", l);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值