九度oj 题目1411:转圈
生活随笔
收集整理的這篇文章主要介紹了
九度oj 题目1411:转圈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 題目描述:
-
?
在一個有向圖有n個頂點(編號從1到n),給一個起點s,問從起點出發,至少經過一條邊,回到起點的最短距離。
?
?
- 輸入:
-
?
輸入包括多組,每組輸入第一行包括三個整數n,m,s(1<=n<=500,0<=m<=10000,1<=s<=n),接下來有m行,每行包括三個整數a,b,c(1<=a,b<=n,1<=c<=1000),表示有一條a到b的邊,長度為c。
?
?
- 輸出:
-
?
對每組輸入。輸出最短距離,如果沒有這個一條路徑輸出"help!"。
?
?
?
?
- 樣例輸入:
-
5 6 1 1 2 1 2 3 2 3 4 1 4 5 1 3 1 3 4 1 1
- 樣例輸出:
-
5
看網上的做法,都使用迪杰斯特拉算法做的,而我采用的是廣度優先搜索的辦法
但一開始的代碼提交錯誤,如下1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <queue> 5 #include <vector> 6 using namespace std; 7 8 int n,m,s; 9 queue <int> que; 10 typedef pair<int, int> Edge; 11 vector<Edge> edge[502]; 12 int step[502]; 13 14 int main(int argc, char const *argv[]) 15 { 16 while(scanf("%d %d %d",&n,&m,&s) != EOF) { 17 while(!que.empty()) { 18 que.pop(); 19 } 20 for(int i = 0; i < n; i++) { 21 edge[i].clear(); 22 } 23 memset(step, 0, sizeof(step)); 24 while(m--) { 25 int a, b, d; 26 scanf("%d %d %d",&a,&b,&d); 27 edge[a].push_back(Edge(b,d)); 28 } 29 que.push(s); 30 while(!que.empty()) { 31 int p = que.front();que.pop(); 32 int sizep = edge[p].size(); 33 34 for(int i = 0; i < sizep; i++) { 35 int tp = edge[p][i].first; 36 int ct = edge[p][i].second; 37 int pt = step[p] + ct; 38 if(step[tp] == 0 || pt < step[tp]) { 39 step[tp] = pt; 40 que.push(tp); 41 } 42 } 43 } 44 if(step[s] == 0) { 45 puts("help!"); 46 } 47 else { 48 printf("%d\n",step[s]); 49 } 50 } 51 return 0; 52 }
這段代碼犯了兩個錯誤,一是20行, clear不應該只到n,萬一第二次輸入的n比第一次的n小呢?
第二是題目中有 起點s到起點s的邊,需要特殊處理,代碼如下
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <queue> 5 #include <vector> 6 using namespace std; 7 8 int n,m,s; 9 queue <int> que; 10 typedef pair<int, int> Edge; 11 vector<Edge> edge[502]; 12 int step[502]; 13 14 int main(int argc, char const *argv[]) 15 { 16 freopen("input.txt","r",stdin); 17 while(scanf("%d %d %d",&n,&m,&s) != EOF) { 18 while(!que.empty()) { 19 que.pop(); 20 } 21 for(int i = 0; i < 502; i++) { 22 edge[i].clear(); 23 } 24 memset(step, 0, sizeof(step)); 25 while(m--) { 26 int a, b, d; 27 scanf("%d %d %d",&a,&b,&d); 28 edge[a].push_back(Edge(b,d)); 29 } 30 que.push(s); 31 while(!que.empty()) { 32 int p = que.front();que.pop(); 33 int sizep = edge[p].size(); 34 35 for(int i = 0; i < sizep; i++) { 36 int tp = edge[p][i].first; 37 int ct = edge[p][i].second; 38 int pt = step[p] + ct; 39 if(p == s) { 40 pt = ct; 41 } 42 if(step[tp] == 0 || pt < step[tp]) { 43 step[tp] = pt; 44 que.push(tp); 45 } 46 } 47 } 48 if(step[s] == 0) { 49 puts("help!"); 50 } 51 else { 52 printf("%d\n",step[s]); 53 } 54 } 55 return 0; 56 }
?
轉載于:https://www.cnblogs.com/jasonJie/p/5813772.html
總結
以上是生活随笔為你收集整理的九度oj 题目1411:转圈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PET多少钱啊?
- 下一篇: 男孩疝气会导致不孕不育吗