poj 2387

无向图,n到1,最短路 spfa,模板题

#include
#include
#include
#include
#include
using namespace std;
#define f first
#define s second
typedef long long LL;
typedef pair PII;
typedef pair PLL;
const int N = 1e3 + 10;
const int M = 2e3 + 10; 
const int INF = 1e9 ;
int inq[N],d[N];
int t,n;
int h[N],to[M*2],nt[M*2],cost[M*2],cnt;

void add(int u,int v,int c){
	to[++cnt] = v;
	cost[cnt] = c;
	nt[cnt] = h[u];
	h[u] = cnt;
}
void spfa(){
	for(int i = 1; i <= n; i++) d[i] = INF;
	d[n] = 0 ; 
	deque q;
	q.push_back(n);
	while(!q.empty()){
		int u = q.front();
		q.pop_front();
		inq[u] = 0;
		for(int i = h[u] ; i ; i = nt[i]){
			int t = to[i];
			int di = cost[i];
			if(d[t] > d[u] + di) {
				d[t] = d[u] + di;
				if(inq[t] == 0){
					inq[t] = 1;
					if(!q.empty() && d[t] < d[u])
						q.push_front(t);
					else q.push_back(t);
				}
			}
		}
	}
}
int main(){
	//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	cin>>t>>n;
	for(int i = 0 ; i < t; i ++) {
		int a,b,c;
		cin>>a>>b>>c;
		add(a,b,c);
		add(b,a,c);
	}
	spfa();
	cout<

你可能感兴趣的:(最短路,poj,2387)