优先队列Dijkstra最短路模板---校赛D KJZ的有向图

最简单写法Floyd还有最短路算法的介绍见之前的博客:

点这里

 

优先队列做最短路比SPFA更稳定,主要是松弛操作的优化

  • 找最小值的(即出队解决)
  • 更新最小值(即入队解决)
  • 两个for循环O(n),松弛操作优化成O(logn)
  • 邻接表优化,变成O(Elogn)

配对堆进一步优化(转自大佬)

部分套用大师兄的代码风格

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

typedef long long LL;
typedef pair<int,int> pii;

const int N = 1e4 + 10;
const LL inf = (LL)1e16;

vector<pii> V[N];
int n, m;
bool vis[N];
LL dis[N];

LL cnt[N][N];

struct Node{
	int id;
	LL d;
	Node(){}
	Node(int id, LL d):id(id),d(d){}
	bool operator < (const Node &A)const{
		return d > A.d;
	}  //也可用cmp比较两个结构体 
};

LL solve(int st){
	for(int i=1; i<=n; i++){
		
		vis[i] = 0;
		dis[i] = inf;
	}

	dis[st] = 0;
	priority_queue<Node> Q;
	Q.push(Node(st, 0));
	Node nd;

	while(!Q.empty()){
		nd = Q.top();
		 Q.pop();
		if(vis[nd.id])	continue;
		for(int i=0; i<V[nd.id].size(); i++){  //vector从0开始 
			int j = V[nd.id][i].first;
			int k = V[nd.id][i].second;
			if(nd.d + k < dis[j]){
				dis[j] = nd.d + k;
				Q.push(Node(j, dis[j]));
			}
		}
	}

	LL ret ;
	for(int i=1; i<=n; i++){
	
		cnt[st][i]=dis[i];
	}

}

int main(){
	
	int x, y, z;
	scanf("%d", &n);  //部分题输入边 
		for(int i=1; i<=n; i++){
			
			V[i].clear();//如果有多组数据,记得清空 
		}
		//按矩阵输入
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=n;j++)
			{
				scanf("%d",&z);
				if(z!=0)
				V[i].push_back(make_pair(j,z));//有向图只有加一次边 
			}
		 } 
		//scanf("%d %d", &st, &ed);
		//while(m--){                //按边输入 
		//	scanf("%d %d %d", &x, &y, &z);
		//	V[x].push_back(make_pair(y, z));
		//	V[y].push_back(make_pair(x, z));//无向图,记得一次添加两条边 
		//}
		
		for(int i=1;i<=n;i++)
		solve(i);
		
		cin>>m;
		
		while(m--)
		{
			scanf("%d %d",&x,&y);
			if(cnt[x][y]!=inf)
			printf("1\n");
			else
			printf("0\n");
		}
		
		
		
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值