60分求助!不知道该怎么优化dij了
查看原帖
60分求助!不知道该怎么优化dij了
856309
oiyang楼主2023/6/28 18:29
#include <bits/stdc++.h>
using namespace std;
int n,p,c;
const int maxcow=505;
const int maxp=805;
const int maxline=1500;
int mc[maxline];
int head[maxline],k;
struct edge{int to,pre,w;}line[maxline];
void addline(int u,int v,int w)
{
	k++;
	line[k].to=v;
	line[k].pre=head[u];
	line[k].w=w;
	head[u]=k;
}
const int INF=0x7fffffff;
long long ans=INF;
struct node
{
	int pos,d;
	friend bool operator <(const node &x,const node &y)
	{
		return x.d>y.d;
	}
};
priority_queue<node>q;
int dis[maxline];
bool vis[maxline];
void dij(int zd)
{
	for(int i=1;i<=p;i++)
		vis[i]=0;
	for(int i=1;i<=p;i++)
		dis[i]=INF;
	dis[zd]=0;
	while(!q.empty())
		q.pop();
	q.push((node){zd,0});
	while(!q.empty())
	{
		node top=q.top();
		q.pop();
		int temppos=top.pos;
		if(vis[temppos])
			continue;
		vis[temppos]=1;
		for(int i=head[temppos];i;i=line[i].pre)
		{
			int v=line[i].to;
			if(dis[v]>dis[temppos]+line[i].w && !vis[v])
			{
				dis[v]=dis[temppos]+line[i].w;
				q.push((node){v,dis[v]});
			}
		}
	}
}
int read()
{
	int x=0,f=1;
	char ch;
	ch=getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch=='-')
			f=-1;
		ch=getchar();
	}
	while(ch>='0' && ch<='9')
		x=x*10+ch-'0',ch=getchar();
	return x*f;
}
int main()
{
	ios::sync_with_stdio(false);
	n=read(),p=read(),c=read();
	for(int i=1;i<=n;i++)
		mc[i]=read();
	for(int i=1;i<=c;i++)
	{
		int u,v,w;
		u=read(),v=read(),w=read();
		addline(u,v,w);
		addline(v,u,w);
	}
	for(int i=1;i<=p;i++)
	{
		long long tempans=0;
		dij(i);
		for(int j=1;j<=n;j++)
			tempans+=dis[mc[j]];
		ans=min(ans,tempans);
	}
	cout<<ans;
	return 0;
}
2023/6/28 18:29
加载中...