萌新求助 TLE on 11
查看原帖
萌新求助 TLE on 11
124152
AmamiyaYuuko楼主2022/2/23 01:17

感觉不可能 TLE 的代码怎么都过不了,怎么会是呢。

#include <bits/stdc++.h>

template <class T>
inline void read(T &x) {
    x = 0;
    int f = 0;
    char ch = getchar();
    while (!isdigit(ch))    { f |= ch == '-'; ch = getchar(); }
    while (isdigit(ch))     { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
    x = f ? -x : x;
    return ;
}

typedef long long LL;
typedef unsigned long long uLL;

struct Edge {
	int to, w;
	Edge(const int &ito, const int &iw) : to(ito), w(iw) {}
};

std::queue<int> q;
std::vector<Edge> g[5010];
int pre[5010][5010], f[5010][5010];
int d[5010];
int n, m, k, ans;
bool vis[5010];

void print(int u, int x) {
	if (u == 1) {
		printf("%d ", u);
		return ;
	}
	print(pre[u][x], x - 1);
	printf("%d ", u);
}

void dfs(int x) {
    vis[x] = true;
    for (auto i : g[x]) {
        dfs(i.to);
    }
}

int main() {
	memset(f, 0x3f, sizeof(f));
	read(n), read(m), read(k);
	for (int i = 1, u, v, w; i <= m; ++i) {
		read(u), read(v), read(w);
		g[u].emplace_back(v, w);
	}
	dfs(1);
	for (int i = 1; i <= n; ++i) {
	    if (vis[i]) {
            for (auto j : g[i]) {
                if (vis[j.to]) {
                    ++d[j.to];
                }
            }   
	    }
	}
	f[1][1] = 0;
	q.push(1);
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		for (auto i : g[u]) {
			int v = i.to;
			--d[v];
			if (!d[v])	q.push(v);
			for (int j = 0; j < n; ++j) {
				if (f[u][j] + i.w <= k && f[u][j] + i.w < f[v][j + 1]) {
					f[v][j + 1] = f[u][j] + i.w;
					pre[v][j + 1] = u;
				}
			}
		}
	}
	for (int i = n; i; --i) {
		if (f[n][i] <= k) {
			ans = i;
			break;
		}
	}
	printf("%d\n", ans);
	print(n, ans);
	puts("");
	return 0;
}
2022/2/23 01:17
加载中...