为什么本题用spfa比dij快呢
查看原帖
为什么本题用spfa比dij快呢
757101
junee楼主2024/4/26 16:18
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int N=220;
int h[N],e[N],ne[N],w[N],idx;
LL dist[N];
int st[N];
int n,m,k,ee,d;
LL f[N],cost[N][N],t[N][N];
int bk[N];
void add(LL a,LL b,LL c){
	e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}
void dijkstra(){
	for(int i=1;i<=m;i++)dist[i]=2e9;
	memset(st,0,sizeof st);
	priority_queue<PII,vector<PII>,greater<PII>>q;
	q.push({0,1});
	dist[1]=0;
	while(q.size()){
		int ver=q.top().second;q.pop();
		if(st[ver])continue;
		st[ver]=1;
		for(int i=h[ver];~i;i=ne[i]){
			int j=e[i];
			if(bk[j])continue;
			if(dist[j]>dist[ver]+w[i]){
				dist[j]=dist[ver]+w[i];
				q.push({dist[j],j});
			}
		}
	}
}
void build(int a,int b){
	memset(bk,0,sizeof bk);
	for(int i=2;i<m;i++){
		for(int j=a;j<=b;j++){
			if(t[i][j])bk[i]=1;
		}
	}
}
int main(){
	memset(h,-1,sizeof h);
	cin>>n>>m>>k>>ee;
	for(int i=1;i<=ee;i++){
		int a,b,c;
		cin>>a>>b>>c;
		add(a,b,c);
		add(b,a,c);
	}
	cin>>d;
	for(int i=1;i<=d;i++){
		int a,b,c;
		cin>>a>>b>>c;
		for(int i=b;i<=c;i++)t[a][i]=1;
	}
	for(int i=1;i<=n;i++){
		for(int j=i;j<=n;j++){
			build(i,j);
			dijkstra();
			cost[i][j]=dist[m];
		}
	}
	for(int i=1;i<=n;i++)f[i]=2e9;
	for(int i=1;i<=n;i++){
		f[i]=cost[1][i]*i;
		for(int j=i-1;j>=0;j--){
			f[i]=max(f[i],f[j]+cost[j+1][i]*(i-j)+k);
		}
	}
	cout<<f[n];
	return 0;
}

2024/4/26 16:18
加载中...