为什么链式前向星会 TLE?
查看原帖
为什么链式前向星会 TLE?
1266809
_0_px楼主2025/6/15 12:27

rt。

链式前向星代码:

#include <bits/stdc++.h>
using namespace std;
namespace Chain_Forward_Star { // 链式前向星
    constexpr int NR = 2e3 + 5, MR = 8e3 + 5;
    struct graph {
        int hd[NR], idx = 1;
        struct edge {
            int to, nxt;
        }e[MR];
        void add(int u, int v) {
            e[++idx] = {v, hd[u]};
            hd[u] = idx;
        }
    };
}
using namespace Chain_Forward_Star;
int n, m;
graph g;
int calc1(const int x, const char ch) {
    if (ch == 'Y') return x;
    return x + n;
}
int calc2(const int x, const char ch) {
    if (ch == 'N') return x;
    return x + n;
}
bool vis[NR];
void dfs(const int x, graph g) {
    vis[x] = true;
    for (int i = g.hd[x]; i; i = g.e[i].nxt) {
        if (!vis[g.e[i].to]) dfs(g.e[i].to, g);
    }
    return;
}
bool check(int x) {
    for (int i = 1; i <= n * 2; ++ i) vis[i] = false;
    dfs(x, g);
    for (int i = 1; i <= n; ++ i) {
        if (vis[i] && vis[i + n]) return 0;
    }
    return 1;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    cin >> n >> m;
    while (m --){
        int x, y;
        char a, b;
        cin >> x >> a >> y >> b;
        g.add(calc2(x, a), calc1(y, b));
        g.add(calc2(y, b), calc1(x, a));
    }
    for (int i = 1; i <= n; ++ i) {
        int f1 = check(i), f2 = check(i + n);
        if (f1 && f2) cout << '?';
        else if (f1) cout << 'Y';
        else if (f2) cout << 'N';
        else {
            cout << "IMPOSSIBLE";
            return 0;
        }
    }
    return 0;
}

第 2 个点 TLE 了,把链式前向星改成邻接表(vector)就 AC 了。

2025/6/15 12:27
加载中...