TLE了,求助
  • 板块CF117C Cycle
  • 楼主jeffstart
  • 当前回复26
  • 已保存回复26
  • 发布时间2023/9/30 14:22
  • 上次更新2023/11/2 16:59:21
查看原帖
TLE了,求助
482998
jeffstart楼主2023/9/30 14:22
#include <bits/stdc++.h>
using namespace std;

const int N = 5010;
vector<int> G[N];
int pos = -1;
vector<int> vec;
bool visited[N];

void dfs(int u, int step, int fa, int uu) {
    if (step == 3) {
        if (u == uu) {
            pos = u;
        }
        return;
    }
    if (visited[u]) {
        return;
    }
    visited[u] = true;
    for (auto v : G[u]) {
        if (v != fa) {
            dfs(v, step + 1, u, uu);
        }
    }
}

void dfs2(int u, int step) {
    if (step > 3) {
        return;
    }
    if (u == pos && step) {
        vec.pop_back();
        for (auto x : vec) {
            cout << x << " ";
        }
        cout << "\n";
        exit(0);
    }
    for (auto v : G[u]) {
        vec.push_back(v);
        dfs2(v, step + 1);
        vec.pop_back();
    }
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        string s;
        cin >> s;
        for (int j = 1; j <= n; j++) {
            int op = s[j - 1] - '0';
            if (op) {
                G[i].push_back(j);
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        memset(visited, false, sizeof(visited));
        dfs(i, 0, -1, i);
        if (pos != -1) {
            break;
        }
    }
    if (pos != -1) {
        memset(visited, false, sizeof(visited));
        vec.push_back(pos);
        dfs2(pos, 0);
    } else {
        cout << pos << " ";
    }
    return 0;
}

这不是 O(n2)O(n^2) 的复杂度吗?
为啥超时了呢?

2023/9/30 14:22
加载中...