dij()算法

dij大致板子

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mpt[505][505];
ll dist[505];
bool s[300];
ll ans=0;
ll n,m;
	
ll  dij(){

	ll tmin=1e7,k=0;
	s[1]=1;
	for(int i=1;i<=n;i++){
		
		tmin=1e7;
		
		for(int j=1;j<=n;j++){
			
			
			if(dist[j]<tmin&&!s[j]){
				
				tmin=dist[j];
				k=j;
				
			}
		}
		
		
		s[k]=1;
		for(int i=1;i<=n;i++){
			
			if(!s[i]&&dist[i]>dist[k]+mpt[k][i]+(i-k+1<=m?(i-k+1)*(i-k+1):(i-k+1-m)*(i-k+1-m)+m*m))
			dist[i]=dist[k]+mpt[k][i]+(i-k+1<=m?(i-k+1)*(i-k+1):(i-k+1-m)*(i-k+1-m)+m*m);
			
		}
	}
	return dist[n];
	
	
}
int main(){

	cin>>n>>m;
	for(int i=0;i<=n+m+10;i++){dist[i]=2e7;s[i]=0;}
	memset(mpt,0,sizeof mpt);
	dist[0]=0;
    for(int i=1;i<=n;i++){
    	ll tpsum=0;
    	for(int j=1;j<=m;j++){
    		
    		cin>>mpt[i][j];	
    		tpsum+=mpt[i][j];
	
		
    		dist[i+j-1]=min(dist[i+j-1],dist[i-1]+tpsum+j*j);
				if(i==1&&j==1)	dist[1]=mpt[1][1]+1;
	cout<<i+j-1<<" "<<dist[i+j-1]<<endl;
		}
	}
cout<<dist[1]<<" "<<dist[n]<<endl;
	cout<<dij();
	
	return 0;
} 
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页