关于Dijkstra
查看原帖
关于Dijkstra
501865
TheSky233楼主2022/1/21 22:11

不是,我不理解

写的Dijkstra反复改来改去提交了好几遍都没过

是优先队列写错了还是Dijkstra写错了/youl/youl/youl

/px/px/px/px/px/px/px/px/px/px/px/px

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

struct node{
	int to,w,next;
}G[1005555];

struct edge{
	int V,E;
	friend bool operator <(edge a,edge b){
		return a.V>b.V;
	}
};

int read(){
	int f=1; int num=0;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-f; ch=getchar();}
	while(ch>='0'&&ch<='9'){num=(num<<1)+(num<<3)+(ch^48); ch=getchar();};
	return num*f;
}

map<string,int> m;
int T,n,p,head[10005],cnt,ask,n1,n2;
int dist[10005];
bool visited[10005];
string name;
string a1,a2;

void Add(int u,int v,int w){
	G[++cnt].to=v; G[cnt].w=w; G[cnt].next=head[u]; head[u]=cnt;
}

void Dijkstra(int S,int T){
	for(int i=1;i<=n;i++) dist[i]=INF;
	for(int i=1;i<=n;i++) visited[i]=0;
	priority_queue<edge> q;
	dist[S]=0;
	q.push((edge){S,0});
	while(!q.empty()){
		edge f=q.top(); q.pop();
		int v=f.V;
		if(v==T) return; 
		if(visited[v]) continue;
		visited[v]=1;
		for(int i=head[v];i;i=G[i].next){
			int t=G[i].to;
			if(!visited[t] && dist[v]+G[i].w<dist[t]){
				dist[t]=dist[v]+G[i].w;
				q.push((edge){t,dist[t]});
			}
		} 
	}
}

int main(){
	T=read();
	while(T--){
		n=read();
		for(int i=1;i<=n;i++){
			cin>>name;
			m[name]=i;
			p=read();
			for(int j=1;j<=p;j++){
				int v,w;
				v=read(); w=read();
				Add(i,v,w);
			}
		}
		ask=read();
		while(ask--){
			cin>>a1>>a2;
			n1=m[a1],n2=m[a2];
			if(n1==n2) {printf("0\n");}
			Dijkstra(n1,n2);
			printf("%d\n",dist[n2]);
		}
		m.clear();
		for(int i=1;i<=cnt;i++)G [i].to=G[i].next=G[i].w=0;
		for(int i=1;i<=n;i++) head[i]=0;
		cnt=0;
	}
	return 0;
}
2022/1/21 22:11
加载中...