码迷,mamicode.com
首页 > 其他好文 > 详细

Age of Moyu (2018 Multi-University Training Contest 7)

时间:2018-10-22 20:47:19      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:memset   printf   print   hustoj   get   typedef   开始   bit   code   

题目链接

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 inline ll read(){
 5     int x=0,f=1;char ch=getchar();
 6     while(ch>9||ch<0){if(ch==-)f=-1;ch=getchar();}
 7     while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();}
 8     return x*f;
 9 }
10 
11 /***********************************************************/
12 
13 const int maxn = 100010;
14 int n, m;
15 int dis[maxn], head[maxn], look[maxn];
16 queue<int>q;
17 int ans, cas;
18 
19 struct Edge
20 {
21     int u, v, w, next, vis;
22 }edge[maxn*4];
23 
24 void add_edge(int u, int v, int w){
25     edge[cas].u = u; edge[cas].v = v; edge[cas].w = w;
26     edge[cas].next = head[u]; edge[cas].vis = 0;
27     head[u] = cas++;
28 }
29 
30 void dfs(int rt, int cl, int num){
31     if(rt == n) {
32         ans = num;
33         return;
34     }
35     if(!look[rt]){
36         look[rt] = 1;
37         dis[rt] = num;
38         q.push(rt);
39     }
40     for(int i = head[rt];i != -1;i = edge[i].next){
41         if(edge[i].vis) continue;
42         if(edge[i].w == cl){
43             edge[i].vis = 1;
44             dfs(edge[i].v, cl, num);
45         }
46     }
47     return;
48 }
49 
50 int bfs(){
51     while(!q.empty()) q.pop();
52     q.push(1);            //从一开始走
53     dis[1] = 0;
54     look[1] = 1;
55     while(!q.empty()){
56         int now = q.front(); q.pop();
57         for(int i = head[now];i != -1;i = edge[i].next){
58             if(edge[i].vis) continue;    //每条边只走一次
59             int v = edge[i].v;
60             edge[i].vis = 1;
61             dfs(v, edge[i].w, dis[now]+1);    //把所有与当前路径相同权值的路径加入
62             if(ans > 0) break;
63         }
64         if(ans > 0) break;
65     }
66     return ans;
67 }
68 
69 void init(){
70     cas = 0;
71     memset(head, -1, sizeof(head));
72     memset(look, 0, sizeof(look));
73     memset(dis, 0x7f, sizeof(dis));
74 }
75 
76 int main(){
77     while(~scanf("%d%d", &n, &m)){
78         init();
79         for(int i = 1;i <= m;i++){
80             int u, v, w;
81             u = read(); v = read(); w = read();
82             add_edge(u, v, w);
83             add_edge(v, u, w);
84         }
85         ans = -1;
86         ans = bfs();
87         printf("%d\n", ans);
88     }
89     return 0;
90 }

 

Age of Moyu (2018 Multi-University Training Contest 7)

标签:memset   printf   print   hustoj   get   typedef   开始   bit   code   

原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/9831691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!