题目描述
这道题就是在上一道模板题的基础上做些改动.
这道题不用创建备份数组,因为边的权值不会影响起点到这个点的距离,也就是dist[]的值.
那么同样最后的输出条件也就不用变化,spfa() == 0x3f3f3f3f;
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n,m,x,y,z,idx;
int e[N],ne[N],h[N],w[N],dist[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx] = b;w[idx] = c; ne[idx] = h[a];h[a] = idx++;
}
int spfa()
{
queue<int> q; q.push(1);
dist[1] = 0;
st[1] = true;//true代表访问过了
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t] ; i != -1 ; i = ne[i])
{
int j = e[i];
if(dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return dist[n];
}
int main()
{
scanf("%d%d",&n,&m);
memset(dist,0x3f,sizeof dist);
memset(h,-1,sizeof h);
while(m--)
{
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
int t = spfa();
if(t == 0x3f3f3f3f) cout << "impossible" << endl;
else printf("%d",t);
return 0;
}