Luogu 4779(dijkstra+线段树优化)(dijkstra+堆优化)

传送门

题意:模板题,求有向非负权图的单源最短路

题解:

明说了要卡SPFA,所以只能dijkstra+数据结构优化,不管用堆还是线段树,只有能到O(nlogn)就OK。

实测线段树略快。

注意:每次“出队”时将当前点赋值为INF(如果硬要做删除操作就只有上平衡树了233),线段树在判断“队列为空”的边界时直接判断全局最小值是否等于INF即可。

线段树优化dijkstra:

#include
#include
#include
#include
#include
using namespace std;
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define root 1,1,n 
const int N=1e5+4,M=2e5+4,INF=0x3f3f3f3f;
int n,m,S;
int head[N],etot=0,dis[N];
int mn[N<<2]; 
struct EDGE {
	int v,nxt,w;
}e[M];
inline void adde(int u,int v,int w) {
	e[etot].nxt=head[u],e[etot].v=v,e[etot].w=w,head[u]=etot++;
}
inline int read() {
	int x=0;char c=getchar();
	while (c<'0'||c>'9') c=getchar();
	while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
	return x;
}/*
struct Node {
	int id,dis;
	Node (int _id=0,int _dis=0):id(_id),dis(_dis) {}
};*/
inline void pushup(int rt) {
	mn[rt]=min(mn[rt<<1],mn[rt<<1|1]);
}
void modify(int rt,int l,int r,int pos,int val) {
	if (l==r) {
		mn[rt]=val;
		return ;
	}
	int mid=l+r>>1;
	if (pos<=mid) modify(lson,pos,val);
	else modify(rson,pos,val);
	pushup(rt);
}
int query(int rt,int l,int r) {
	if (l==r) return l;
	int mid=l+r>>1;
	if (mn[rt<<1]dis[p]+e[i].w) {
				dis[v]=dis[p]+e[i].w;
				modify(root,v,dis[v]);
			}
		}
	}
}
int main() {
//	freopen("P4779.txt","r",stdin);
	memset(head,-1,sizeof(head));
	memset(mn,INF,sizeof(mn));
	n=read(),m=read(),S=read();
	for (register int i=0;i

堆优化dijkstra:

#include
#include
#include
#include
#include
using namespace std;
const int N=1e5+4,M=2e5+4;
int n,m,S;
int head[N],etot=0,dis[N];
struct EDGE {
	int v,nxt,w;
}e[M];
struct Node {
	int id,dis;
	friend bool operator <(const Node &a,const Node &b) {
		return a.dis>b.dis;
	}
};
inline void adde(int u,int v,int w) {
	e[etot].nxt=head[u],e[etot].v=v,e[etot].w=w,head[u]=etot++;
}
inline int read() {
	int x=0;char c=getchar();
	while (c<'0'||c>'9') c=getchar();
	while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
	return x;
}
inline void dijkstra(int S) {
	priority_queue q;
	memset(dis,0x3f,sizeof(dis));
	q.push((Node){S,dis[S]=0});
	while (!q.empty()) {
		Node cur=q.top();
		q.pop();
		int p=cur.id;
		if (cur.dis^dis[p]) continue;
		for (int i=head[p];~i;i=e[i].nxt) {
			int v=e[i].v;
			if (dis[v]>dis[p]+e[i].w) {
				dis[v]=dis[p]+e[i].w;
				q.push((Node){v,dis[v]});
			}
		}
	}
}
int main() {
	freopen("P4779.txt","r",stdin);
	memset(head,-1,sizeof(head));
	n=read(),m=read(),S=read();
	for (register int i=0;i

 

你可能感兴趣的:(模板,图论)