【USACO 2011】 道路和航线

【题目链接】

              点击打开链接

【算法】

           SPFA + SLF / LLL 优化

【代码】

           

#include<bits/stdc++.h>
using namespace std;
#define MAXT 25000

int i,T,R,P,S,u,v,w;
int dist[MAXT+10],vis[MAXT+10];
vector<pair<int,int> > E[MAXT+10];

template <typename T> void read(T &x) {
		int f=1; char c = getchar(); x=0;
		for (; !isdigit(c); c = getchar()) { if (c=='-') f=-1; }
		for (; isdigit(c); c = getchar()) x=x*10+c-'0';
		x*=f;
}

inline void SPFA() {
		int i,x,to,cost;
		deque<int> q;
		for (i = 1; i <= T; i++) dist[i] = 2e9;
		dist[S] = 0; 
		q.push_back(S);
		while (!q.empty()) {
				x = q.front(); q.pop_front();
				vis[x] = 0;
				for (i = 0; i < E[x].size(); i++) {
						to = E[x][i].first;
						cost = E[x][i].second;
						if (dist[x] + cost < dist[to]) {
								dist[to] = dist[x] + cost;
								if (!vis[to]) {
										vis[to] = 1;
										if ((q.empty()) || (dist[to] > dist[q.front()])) q.push_back(to);
										else q.push_front(to);
								}
						}
				} 
		}
}

int main() {
		
		read(T); read(R); read(P); read(S);
		
		for (i = 1; i <= R; i++) {
				read(u); read(v); read(w);
				E[u].push_back(make_pair(v,w));
				E[v].push_back(make_pair(u,w));	
		} 
		for (i = 1; i <= P; i++) {
				read(u); read(v); read(w);
				E[u].push_back(make_pair(v,w));	
		}
		
		SPFA();
		
		for (i = 1; i <= T; i++) {
				if (dist[i] == 2e9)
						cout<< "NO PATH" << endl;
				else cout<< dist[i] << endl;
		}
		
		return 0;
	
}

猜你喜欢

转载自blog.csdn.net/even_bao/article/details/80298213