Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others) Total Submission(s): 1483 Accepted Submission(s): 451 Problem Description Mr.Quin love fishes so much and Mr.Quin’s city has a nautical system,consisiting of N ports and M shipping lines. The ports are numbered 1 to N . Each line is occupied by a Weitian. Each Weitian has an identification number. Input There might be multiple test cases, no more than 20 . You need to read till the end of input. Output For each test case output the minimum required cost. If Mr.Quin can’t travel to port N , output −1 instead. Sample Input 3 3
扫描二维码关注公众号,回复:
3547459 查看本文章
1 2 1 1 3 2 2 3 1 2 0 3 2 1 2 1 2 3 2 Sample Output 1 -1 2 |
题意:有n个点,m条边,如果存在边a-b-c,从a走到b,若ab的权值==bc的权值,则路径为1,反之路径为2。现在求从1到n的最短路;
思路:优先队列的迪杰特斯拉;
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
vector<int>edge[100005];
vector<int>dis[100005];
int v[100005];
int d[100005];
struct Node
{
int last;
int w;
int id;
}x[100005];
bool operator <(Node A,Node B)
{
return (A.w>B.w);
}
void dij(int k)
{
priority_queue<Node>q;
memset(v,0,sizeof(v));
q.push(x[k]);
while(!q.empty())
{
Node temp=q.top();
int index=temp.id;
//cout<<index<<endl;
if(v[index]==1)continue;
q.pop();
for(int i=0;i<edge[index].size();i++)
{
int dot=edge[index][i];
int tempDis=d[index];
if(x[index].last!=dis[index][i])
tempDis=d[index]+1;
if(d[dot]>tempDis)
{
d[dot]=tempDis;
x[dot].last=dis[index][i];
x[dot].w=d[dot];
q.push(x[dot]);
}
}
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)d[i]=1000000+10,x[i].id=i;
for(int i=1;i<=100000;i++)dis[i].clear(),edge[i].clear();
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
edge[a].push_back(b);
edge[b].push_back(a);
dis[a].push_back(c);
dis[b].push_back(c);
}
x[1].last=-1;
d[1]=0;
x[1].w=0;
dij(1);
if(d[n]==1000000+10)
printf("-1\n");
else
printf("%d\n",d[n]);
}
return 0;
}