spfa和迪杰斯特拉(邻接表)

这个算spfa模板吧...本来想用来解Til the Cows Come Home POJ - 2387 ,但是。。有重边....所以。用邻接表的话..重边问题我暂时不知道怎么解决...只能用邻接矩阵做了..然后  这个就用作spfa模板吧 

感觉。。。如果用队列的话,迪杰斯特拉和spfa之间应该就是vis[]用处不同了....毕竟,spfa可以判断负回环

 

#include 
#include 

using namespace std;

const int INFTY = 0x3f3f3f3f;
const int MAXM = 4005;
const int MAXV = 1005;

typedef struct{
	int a, b, w, next;
}Edge;

Edge edge[MAXM];
int n, m, headlist[MAXV];

void spfa()
{ 
	int d[MAXV], vis[MAXV];
	queue q;

	for(int i = 2; i <= n; i++) {
		d[i] = INFTY;
		vis[i] = 0;
	}

	d[1] = 0;
	vis[1] = 0;
	q.push(1);

	while(!q.empty()) {

		int v = q.front(); 
		q.pop();

		vis[v] = 0;
 
		for(int i = headlist[v]; i != -1; i = edge[i].next)
			if(d[v] + edge[i].w < d[edge[i].b]) {
				d[edge[i].b] = d[v] + edge[i].w;
	//			cout << edge[i].a << "->" << edge[i].b << endl;
                                if(!vis[edge[i].b])
				    q.push(edge[i].b);
                                vis[edge[i].b] = 1;
 			}
	}

	cout << d[n] << endl;
}

void addedge(int a, int b, int c, int i)
{
		edge[i].a = a;
		edge[i].b = b;
		edge[i].w = c;
		edge[i].next = headlist[a];
		headlist[a] = i;
 } 

int main() {

	int a, b, c;

	while(cin >> m >> n) { 
		for(int i = 1; i <= n; i++) headlist[i] = -1;

		for(int i = 1; i <= 2 * m; i += 2) {
			cin >> a >> b >> c;

	    	addedge(a, b, c, i);
	    	addedge(b, a, c, i+1);
		}
		spfa();
	}
	return 0;
}

 

 

#include 
#include 

using namespace std;

const int INFTY = 0x3f3f3f3f;
const int MAXM = 4005;
const int MAXV = 1005;

typedef struct{
	int a, b, w, next;
}Edge;

Edge edge[MAXM];
int n, m, headlist[MAXV];

void Djs()
{ 
	int d[MAXV], vis[MAXV];
	queue q;

	for(int i = 2; i <= n; i++) {
		d[i] = INFTY;
		vis[i] = 0;
	}

	d[1] = 0;
	vis[1] = 0;
	q.push(1);

	while(!q.empty()) {

		int v = q.front(); 
		q.pop();

		if(vis[v])continue;
		vis[v] = 1;
 
		for(int i = headlist[v]; i != -1; i = edge[i].next)
			if(d[v] + edge[i].w < d[edge[i].b]) {
				d[edge[i].b] = d[v] + edge[i].w;
	//			cout << edge[i].a << "->" << edge[i].b << endl;
				q.push(edge[i].b);
 			}
	}

	cout << d[n] << endl;
}

void addedge(int a, int b, int c, int i)
{
		edge[i].a = a;
		edge[i].b = b;
		edge[i].w = c;
		edge[i].next = headlist[a];
		headlist[a] = i;
 } 

int main() {

	int a, b, c;

	while(cin >> m >> n) { 
		for(int i = 1; i <= n; i++) headlist[i] = -1;

		for(int i = 1; i <= 2 * m; i += 2) {
			cin >> a >> b >> c;

	    	addedge(a, b, c, i);
	    	addedge(b, a, c, i+1);
		}
		spfa();
	}
	return 0;
}

 

你可能感兴趣的:(POJ,SPFA)