F - Construct a Palindrome

原题链接

#include <bits/stdc++.h>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

const int N = 1010, M = 4010;

int h1[N], h2[N], e[M], ne[M], w[M], n, m, idx;
int f[N][N];
PII q[N * N];
int ans = 1e9;

void add(int h[], int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}

int bfs(int fr, int to) {
    int hh = 0, tt = -1;
    f[fr][to] = 0;
    q[++ tt] = {fr, to};

    while (hh <= tt) {
        auto t = q[hh ++];
        int t1 = t.x, t2 = t.y;

        for (int i1 = h1[t1]; i1 != -1; i1 = ne[i1])
        for (int i2 = h2[t2]; i2 != -1; i2 = ne[i2]) {
            if (w[i1] != w[i2]) continue;
            int j1 = e[i1], j2 = e[i2];
            if (f[j1][j2] != -1)    continue;
            if (t1 == j2 && t2 == j1)
                ans = min(ans, f[t1][t2] + 1);  //入队不一定最小

            else if (j1 == j2)
                ans = min(ans, f[t1][t2] + 2);  //入队不一定最小

            f[j1][j2] = f[t1][t2] + 2;
            q[++ tt] = {j1, j2};
        }
    }
    if (ans == 1e9) return -1;
    return ans;
}
int main() {
    memset(h1, -1, sizeof h1);
    memset(h2, -1, sizeof h2);
    memset(f, -1, sizeof f);

    cin >> n >> m;
    for (int i = 0; i < m; i ++) {
        int a, b, c;
        char ch[2];
        cin >> a >> b >> ch;
        c = ch[0] - '\0';
        add(h1, a, b, c), add(h1, b, a, c);
        add(h2, a, b, c), add(h2, b, a, c);
    }

    cout << bfs(1, n);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值