dijkstra+堆优化 全RE,求助T^T,自己调试都能过
查看原帖
dijkstra+堆优化 全RE,求助T^T,自己调试都能过
1116222
LTphy楼主2024/7/30 20:00
#include <bits/stdc++.h>
using namespace std;

typedef pair<int,int>PII;
const int N = 100100;

int n,m;
int h[N],e[N],w[N],ne[N],idx;
int h1[N],e1[N],w1[N],ne1[N],xid;
int dist[N],dist1[N];
bool st[N],fst[N];

void add(int a,int b,int c){
	e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void add1(int a,int b,int c){
	e1[xid]=b,w1[xid]=c,ne1[xid]=h1[a],h1[a]=xid++;
}
int dijkstra(){
	priority_queue<PII,vector<PII>, greater<PII> > q;
	
	memset(dist,0x3f,sizeof dist);
    dist[1]=0;
    q.emplace(0,1);
    
    while(q.size()){
    	auto t = q.top();
    	q.pop();
    	
    	int f = t.second;
    	if(st[f]) continue;
    	st[f]=1;
    	
    	for(int i=h[f];i!=-1;i=ne[i]){
    		int j = e[i];
    		if(dist[j]>dist[f]+w[i]){
    			dist[j] = dist[f]+w[i];
    			q.emplace(dist[j],j);
			}
		}
	}
}
void fdijkstra(){
	priority_queue<PII,vector<PII>,greater<PII> >q;
	memset(dist1,0x3f,sizeof dist1);
	dist1[1]=0;
	
	q.emplace(0,1);
	while(q.size()){
		auto t = q.top();
		q.pop();
		
		int f = t.second;
		if(fst[f]) continue;
	       fst[f] = 1;
		
		for(int i=h1[f];i!=-1;i=ne1[i]){
			int j = e1[i];
			if(dist1[j]>dist1[f]+w1[i]){
				dist1[j]=dist1[f]+w1[i]; 
				q.emplace(dist1[j],j);
			}
		}
	}
}
int main(){
	
	memset(h,-1,sizeof h);
	memset(h1,-1,sizeof h1);
	
	scanf("%d%d",&n,&m);
	while(m--){
		int a,b,c;
	     scanf("%d%d%d",&a,&b,&c);
	     add(a,b,c);
	     add1(b,a,c);  //反向建图 
	}
	dijkstra();
	fdijkstra();
	
	int ans = 0;
	for(int i=2;i<=n;i++){
		ans += dist1[i] + dist[i];
	}
	printf("%d",ans);
	return 0;
} 
2024/7/30 20:00
加载中...