为啥TLE,哪里写错了?
查看原帖
为啥TLE,哪里写错了?
255762
lyxleo楼主2022/6/26 19:42

求帮忙,谢谢!

#include <bits/stdc++.h>
using namespace std;
int read();
int n,m;
struct Edge{
	int v,w,nxt;
	Edge(int vv = 0,int ww = 0,int nxtt = 0){
		v = vv;w = ww;nxt = nxtt;
	}
}e[5005];
int p[5005],eid;
void init(){
	memset(p,-1,sizeof(p));
	eid = 0;
}
void insert(int u,int v,int w){
	e[eid].v = v;
	e[eid].w = w;
	e[eid].nxt = p[u];
	p[u] = eid++;
}
bool SPFA();
int d[5005];
bool in_queue[5005];
int spfa_cnt[5005];
queue <int> q;
int main(){
	init();
	n = read();
	m = read();
	for(int i = 1;i <= m;++i){
		int in_a = 0,in_b = 0,in_y = 0;
		in_a = read();
		in_b = read();
		in_y = read();
		insert(in_b,in_a,in_y);
	}
	for(int i = 1;i <= n;++i){
		insert(0,i,0);
	}
	if(SPFA()){
		printf("NO");
	}
	else{
		for(int i = 1;i <= n;++i){
			printf("%d ",d[i]);
		}
	}
	return 0;
}

int read(){
	register int w = 0,flag = 1;
	register char c = getchar();
	while(c < '0' || c > '9'){
		if(c == '-'){
			flag = -1;
		}
		c = getchar();
	}
	while(c >= '0' && c <= '9'){
		w =(w << 3) + (w << 1) + (c ^ 48);
		c = getchar();
	}
	return w * flag;
}

bool SPFA(){
	memset(d,0x3f3f3f3f,sizeof(d));
	d[0] = 0;
	q.push(0);
	in_queue[0] = true;
	++spfa_cnt[0];
	while(!q.empty()){
		int u = q.front();
		q.pop();
		in_queue[u] = false;
		for(int i = p[u];i != -1;i = e[i].nxt){
			int v = e[i].v;
			if(d[v] > d[u] + e[i].w){
				d[v] = d[u] + e[i].w;
				if(in_queue[v] == false){
					++spfa_cnt[v];
					if(spfa_cnt[v] > n){
						return true;
					}
					q.push(v);
					in_queue[v] = true;
				}
			}
		}
	}
	return false;
}
2022/6/26 19:42
加载中...