图论之最短路问题

此种题型最为经典,可以有多种变化形式,但最终所需的模板总是万变不离其宗,这里复习一下模板,并有所改变。

Dijsktra:

#include
#include
#include
#include
#include
#define INF 0x7f7f7f7f
#define maxn 100000
using namespace std;
int n,m;
struct Edge{
	int from,to,dist;
};
struct HeapNode{
	int d,u;
	bool operator < (HeapNode rhs)const{
		return d>rhs.d;
	}
};
struct Dijkstra{
	int n,m;
	vector edges;
	vector G[maxn];
	bool done[maxn];
	int d[maxn];
	int p[maxn];
	void init (int n){
		this->n=n;
		for (int i=0;i Q;
		for (int i=0;id[u]+e.dist){
					d[e.to]=d[u]+e.dist;
					p[e.to]=G[u][i];
					Q.push((HeapNode){d[e.to],e.to});
				}
			}
	    }
	}
}dis;
int v[maxn],w[maxn],u[maxn];
int main(){
	freopen("input.in","r",stdin);
	freopen("output.out","w",stdout);
	scanf("%d %d",&n,&m);
	dis.init(n);
	for (int i=0;i

Spfa:

#include
#include
#include
#include
#include
#define maxn 100000
#define INF 0x7f7f7f7f
using namespace std;
int n,m;
struct Edge{
	int to,dist;
};
struct Spfa{
	int n,m;
	bool inq[maxn];
	int d[maxn];
	vector G[maxn];
	void init(int n){
		this->n=n;
		for (int i=0;i Q;
		memset(inq,0,sizeof(inq));
		for (int i=0;id[u]+e.dist){
					d[e.to]=d[u]+e.dist;
					if (!inq[e.to]){
						Q.push(e.to);
						inq[e.to]=true;
					}
				}
			}
		}
	}
}dis;
int u[maxn],v[maxn],w[maxn];
int main(){
	freopen("input.in","r",stdin);
	freopen("output.out","w",stdout);
	scanf("%d %d",&n,&m);
	dis.init(n);
	for (int i=0;i


你可能感兴趣的:(图论之最短路问题)