Age of Moyu
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 4523 Accepted Submission(s): 430
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 −1instead)
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
题意:n个港口和m条边,没条边都会占用一条航线,航线标号为c,每次航线的变换都会花费1元,求1到n的最小花费。
广搜了一遍 ,但是花费相同到next点的航线不同也需要进队,这样即可包含所有情况了。
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
const int maxm = 200005;
const int INF = 1e9 + 7;
struct node
{
int v, c;
};
vector<node>v[maxm];
int n, dis[maxm], vis[maxm], p[maxm], lc[maxm];
void bfs()
{
queue<int>q;
for (int i = 1;i <= n;i++) dis[i] = INF, lc[i] = -1;
dis[1] = 0, vis[1] = 1;
q.push(1);
while (!q.empty())
{
int u = q.front();q.pop();
for (int i = 0;i < v[u].size();i++)
{
node now = v[u][i];
int len = 0;
if (lc[u] != now.c) len = 1;
//if (u == 2 && now.v == 3) printf("%d %d %d\n", dis[u], dis[now.v],len);
if (dis[now.v] > dis[u] + len || dis[now.v] == dis[u] + len&&lc[now.v] != now.c)
{
lc[now.v] = now.c;
dis[now.v] = dis[u] + len;
q.push(now.v);
}
}
}
}
int main()
{
int i, j, k, sum, t, m, c, x, y;
while (scanf("%d%d", &n, &m)!=EOF)
{
for (i = 1;i <= n;i++) v[i].clear();
for (i = 1;i <= m;i++)
{
scanf("%d%d%d", &x, &y, &c);
node tmp;tmp.c = c;
tmp.v = y, v[x].push_back(tmp);
tmp.v = x, v[y].push_back(tmp);
}
bfs();
if (dis[n] == INF) printf("-1\n");
else printf("%d\n", dis[n]);
}
return 0;
}