最近一直在写最短路的题目!这道题目我本来是想要三种模板来写的,可发现用Floyd写错了,等改对了再来更新这种模板的解法!
Dijkstra:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int map[maxn][maxn];
int map1[maxn][maxn];
int dist[maxn];
int dist1[maxn];
bool p[maxn];
int n,m,x;
void init()
{
int i,j;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
map[i][j]=inf;
map1[i][j]=inf;
}
}
}
void dij(int v,int dist[], int map[][maxn])
{
int i,j,min,pos;
for(i=1; i<=n; i++)
{
p[i]=false;
dist[i]=map[v][i];
}
p[v]=true;
dist[v]=0;
for(i=1; i<n; i++)
{
min=inf;
for(j=1; j<=n; j++)
{
if(!p[j]&&dist[j]<min)
{
min=dist[j];
pos=j;
}
}
p[pos]=true;
for(j=1; j<=n; j++)
{
if(!p[j]&&dist[j]>dist[pos]+map[pos][j])
{
dist[j]=dist[pos]+map[pos][j];
}
}
}
}
int main()
{
int i,j;
while(scanf("%d%d%d",&n,&m,&x)!=EOF)
{
init();
for(i=0; i<m; i++)
{
int a,b,t;
scanf("%d%d%d",&a,&b,&t);
if(a==x)map[a][b]=t;
else if(b==x)map1[b][a]=t;
else
{
map1[b][a]=t;
map[a][b]=t;
}
}
dij(x,dist,map);
dij(x,dist1,map1);
int max_=0;
for(i=1; i<=n; i++)
{
max_=max(max_,dist[i]+dist1[i]);
}
cout<<max_<<endl;
}
return 0;
}
SPFA:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int map[maxn][maxn];
int map1[maxn][maxn];
int dist[maxn];
int dist1[maxn];
bool p[maxn];
int n,m,x;
void init()
{
int i,j;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
map[i][j]=inf;
map1[i][j]=inf;
}
}
}
int SPFA(int v,int dist[], int map[][maxn])
{
int i;
for(i=1; i<=n; i++)
{
p[i]=false;
dist[i]=inf;
}
queue<int>q;
dist[v]=0;
p[v]=true;
q.push(v);
while(!q.empty())
{
int k=q.front();
q.pop();
p[k]=false;
for(i=1; i<=n; i++)
{
if(dist[i]>dist[k]+map[k][i])
{
dist[i]=dist[k]+map[k][i];
if(!p[i])
{
q.push(i);
p[i]=true;
}
}
}
}
return dist[i];
}
int main()
{
int i;
while(scanf("%d%d%d",&n,&m,&x)!=EOF)
{
init();
for(i=1; i<=m; i++)
{
int a,b,t;
scanf("%d%d%d",&a,&b,&t);
if(a==x)map[a][b]=t;
else if(b==x)map1[b][a]=t;
else
{
map[a][b]=t;
map1[b][a]=t;
}
}
SPFA(x,dist,map);
SPFA(x,dist1,map1);
int max_=0;
for(i=1; i<=n; i++)
{
max_=max(max_,dist[i]+dist1[i]);
}
cout<<max_<<endl;
}
return 0;
}
poj3268
最新推荐文章于 2021-09-30 21:06:39 发布