escription
lqp18_31和1tthinking经常出题来虐ftiasch。有一天, lqp18_31搞了一个有向图,每条边的长度都是1。 他想让ftiasch求出点1到点 N 的最短路。"水题啊。", ftiasch这么说道。
所以1tthinking把某些边的长度增加了1(也就是说,每条边的长度不是1就是2)。现在,可怜的ftiasch要向你求助了。
Input
第1行,两个整数 N (1 ≤ N ≤ 105) 和 M (1 ≤ M ≤ 106), 点和边的数量。
第2到 M + 1行: 三个整数 Ui, Vi, Wi (1 ≤ Wi ≤ 2), 从点 Ui 到 Vi 长度为 Wi 的边。
Output
一个整数,表示点1到点N的最短路。数据保证至少存在一条路径。
Sample Input
3 3
1 2 1
2 3 1
1 3 2
Sample Output
2
HINT
Source
题解:
因为有m<=1000000,用spfa或者其他dijkstra堆优化什么的显然要完蛋,所以要用时间效率为O(m)的BFS才行
但是由于边权不为1,显然不能直接BFS,所以要把边权为2的边加一个点,转化成2个边权为1的边
#include <stdio.h>
#include <queue>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn=1000007;
int d[maxn];
int e1;
int t;
int to[maxn],next[maxn],head[maxn];
void addedge(int u,int v){
++e1;
to[e1]=v;
next[e1]=head[u];
head[u]=e1;
}
int bfs(int s){
memset(d,-1,sizeof(d));
queue<int> q;
q.push(s);
d[s]=0;
while(!q.empty()){
int u=q.front();q.pop();
if(u==t) return d[t];
for(int i=head[u];i;i=next[i]){
int v=to[i];
if(d[v]<0){
d[v]=d[u]+1;
q.push(v);
}
}
}
}
int e2;
int main(){
int n,m;
scanf("%d%d",&n,&m);
e2=n;
t=n;
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
if(w==1) addedge(u,v);
else{
++e2;
addedge(u,e2);
addedge(e2,v);
}
}
printf("%d",bfs(1));
return 0;
}