题意:1->n的最短路,边的编号每变动一次权值加一;
分析:
用set||dp维护边的编号,再套上最短路直接写就行;
dfs跑超时了,这很正常。。。我换成dij+set+输入挂也超时。。。把set换成dp(因为对于每个点只需要保存两个编号不同的权值)还是TLE。。。最后把前向星存图将成vector,pair换成结构体,dp将成set,输入挂砍掉给我AC了。。。AC的代码在本地比我前几份代码慢了1500ms,结果硬是给过了,我交了40发。。。傻逼题坑了我半天。。。玄学+菜~ 。。。
#include <bits/stdc++.h>
using namespace std;
#define met(s) memset(s, 0, sizeof(s))
#define rep(i, a, b) for(int i = a; i <= b; ++i)
template <class T> inline void scan_d(T &ret) {
char c; ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9') {
ret = ret * 10 + (c - '0'), c = getchar();}}
typedef long long LL;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int MAXN = 100000 + 5;
int head[MAXN];
int cnt = 0;
struct node {
int to, cost;
node(int to = 0,int cost = 0):to(to),cost(cost){}
};
struct Node {
int to, cost;
Node(int to = 0,int cost = 0):to(to),cost(cost){}
bool operator < (const Node& a) const {
return a.cost < cost;
}
};
priority_queue<Node> que;
vector<node> G[MAXN];
set<int> se[MAXN];
int d[MAXN];
int n, m;
inline void init() {
for(int i = 0; i < MAXN; ++i) se[i].clear(), G[i].clear();
memset(d, INF, sizeof(d));
}
inline void dij(int s) {
d[s] = 0;
que.push(Node(s, 0));
while(!que.empty()) {
Node p = que.top(); que.pop();
int v = p.to;
if(d[v] < p.cost) continue;
for(int i = 0; i < G[v].size(); ++i) {
node e = G[v][i];
int cos = d[v] + !se[v].count(e.cost);
if(d[e.to] < cos) continue;
if(d[e.to] > cos) {
d[e.to] = cos;
se[e.to].clear();
se[e.to].insert(e.cost);
que.push(Node(e.to, d[e.to]));
} else se[e.to].insert(e.cost);
}
}
if(d[n] != INF) printf("%d\n", d[n]);
else puts("-1");
}
int main() {
// freopen("1.in", "r", stdin);
// freopen("2.out", "w", stdout);
int a, b, c;
while(scanf("%d %d", &n, &m) == 2) {
init();
for(int i = 0; i < m; ++i) {
scanf("%d %d %d", &a, &b, &c);
G[a].push_back(node(b, c));
G[b].push_back(node(a, c));
}
dij(1);
}
return 0;
}