明显是可以用最短路来代替动规的题,所以就一发spfa水过去了
对 就是一发spfa
注意建图时得一些细节,比如边界。为了方便按循序个每个点标号
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int map[1000+5][1000+5];
#define N 500500
#define M 2502500
int n;
int head[N],dis[N],vis[N];
struct graph
{
int next, to, val;
graph() {}
graph(int _next, int _to, int _val)
: next(_next), to(_to), val(_val) {}
} edge[M];
int tt=1;
inline void add(int x, int y, int z)
{
static int cnt = 0;
edge[++cnt] = graph(head[x], y, z);
head[x] = cnt;
}
inline int read()
{
int x = 0, f = 1; char 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;
}
void solve(int Line,int Row)
{
if(Line==1&&Row==1)
{
add(1,2,map[2][1]);
add(1,3,map[2][2]);
return ;
}
if(Row==1)
{
add(tt,tt+Line-1,map[Line][Line]);
add(tt,tt+Line,map[Line+1][1]);
add(tt,tt+1,map[Line][2]);
add(tt,tt+Line+1,map[Line+1][2]);
add(tt,tt+2*Line,map[Line+1][Line+1]);
return;
}
else if(Row==Line)
{
add(tt,tt-Line+1,map[Line][1]);
add(tt,tt+Line,map[Line+1][Row]);
add(tt,tt+Line+1,map[Line+1][Row+1]);
add(tt,tt+1,map[Line+1][1]);
add(tt,tt-1,map[Line][Row-1]);
return;
}
else
{
add(tt,tt-1,map[Line][Row-1]);
add(tt,tt+1,map[Line][Row+1]);
add(tt,tt+Line,map[Line+1][Row]);
add(tt,tt+Line+1,map[Line+1][Row+1]);
return;
}
}
queue <int >Q;
void spfa()
{
memset(dis,0x3f,sizeof dis);
int start=1,end=n*(n-1)/2;end++;
dis[start]=0;vis[start]=true;
Q.push(start);
while(!Q.empty())
{
int t=Q.front();
Q.pop();
vis[t]=false;
for(int i=head[t];i;i=edge[i].next)
{
int tmp=edge[i].val;
if(tmp+dis[t]<dis[edge[i].to])
{
dis[edge[i].to]=tmp+dis[t];
if(!vis[edge[i].to])
{
vis[edge[i].to]=true;
Q.push(edge[i].to);
}
}
}
}
printf("%d",dis[end]+map[1][1]);
}
int main()
{
freopen("PE.in", "r", stdin);
freopen("PE.out", "w", stdout);
memset(map,0x3f,sizeof map);
cin>>n;
for(int i=1;i<=n;++i)
for(int j=1;j<=i;++j)
map[i][j]=read();
for(int i=1;i<=n;++i)
for(int j=1;j<=i;++j)
{
solve(i,j);
tt++;
}
//DFS(1);
spfa();
}