HDU 6386 Age of Moyu BFS+優先佇列
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.
The i-th (1≤i≤M) line connects port Ai and Bi (Ai≠Bi) bidirectionally, and occupied by Ci Weitian (At most one line between two ports).
When Mr.Quin only uses lines that are occupied by the same Weitian, the cost is 1 XiangXiangJi. Whenever Mr.Quin changes to a line that is occupied by a different Weitian from the current line, Mr.Quin is charged an additional cost of 1 XiangXiangJi. In a case where Mr.Quin changed from some Weitian A's line to another Weitian's line changes to Weitian A's line again, the additional cost is incurred again.
Mr.Quin is now at port 1 and wants to travel to port N where live many fishes. Find the minimum required XiangXiangJi (If Mr.Quin can’t travel to port N, print −1 instead)
Input
There might be multiple test cases, no more than 20. You need to read till the end of input.
For each test case,In the first line, two integers N (2≤N≤100000) and M (0≤M≤200000), representing the number of ports and shipping lines in the city.
In the following m lines, each contain three integers, the first and second representing two ends Ai and Bi of a shipping line (1≤Ai,Bi≤N) and the third representing the identification number Ci (1≤Ci≤1000000) of Weitian who occupies this shipping line.
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
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條道路,計算從1直接到n的“最短路“,m條道路給出起始點和終止點以及道路標號,當從一條路走到另一條路的時候,如果標號相同則不增加消耗,否則消耗+1
思路:這個題目的資料有問題,很容易水過去,所以這裡學習的是BFS+優先佇列以及vector<node>的使用方法,因為自己實現太弱了
#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 5;
typedef long long ll;
int n,m,ans;
int vis[maxn];
struct node{
int y;
int v;
int cnt;
};
vector<node> c[maxn]; //vector和結構體的使用 第二維是結構體具體看使用
bool operator < (const node &a,const node &b) //過載放在外面 使得在優先佇列中預設這樣的排序
{
return a.cnt>b.cnt;
}
void bfs()
{
priority_queue<node> q; //優先佇列存貯結構體
node now;
for(int i=0;i<c[1].size();i++){
q.push(c[1][i]);
}
vis[1]=1;
while(!q.empty()){
now=q.top();
q.pop();
vis[now.y] = 1;
if(now.y == n){
ans = now.cnt;
return ;
}
node mid;
for(int i = 0; i < c[now.y].size(); i++){
if(vis[c[now.y][i].y]) continue;
if(now.v != c[now.y][i].v) mid.cnt = now.cnt + 1;
else mid.cnt = now.cnt;
mid.y = c[now.y][i].y;
mid.v = c[now.y][i].v;
q.push(mid);
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)==2){
ans=INF;
memset(vis,0,sizeof(vis));
for(int i =0;i<=n;i++)
c[i].clear();
int x,y,v;
while(m--){
scanf("%d%d%d",&x,&y,&v);
node now;
now.y=y; now.v=v; now.cnt=1;
c[x].push_back(now);
now.y=x;
c[y].push_back(now);
}
bfs();
if(ans==INF)
printf("-1\n");
else
printf("%d\n",ans);
}
}