ZOJ - 2750 Idiomatic Phrases Game (最短路徑)

來源:互聯網
上載者:User

題目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1750

題意:

n個成語,前一個成語的最後一個字,與後一個成語的第一個字相同,求最小查詢時間

分析:

有向圖,查詢時間作為權值,Dijkstra演算法

代碼:

#include <stdio.h>#include <iostream>#include <string.h>#include <string>#include <math.h>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>using namespace std;#define MAX 1000#define MIN -1e+10#define INF 0x7f7f7f7fint t, n, m;int Edge[MAX][MAX];int s[MAX]; // 已達點 - 未達點int dist[MAX]; // 由起點出發,到達i的最小距離void Dijkstra(){int i, j;for(i = 1; i<=n; i++) // 起點為1{s[i] = 0;dist[i] = Edge[1][i];}s[1] = 1;dist[1] = 0;for(i = 1; i<n; i++){int mint = INF, v = -1;for(j = 1; j<=n; j++) // 找出當前,由已達點到未達點的最小距離{if(!s[j] && dist[j] < mint){mint = dist[j];v = j;}}if(v == -1) break;s[v] = 1;for(j = 1; j<=n; j++) // 維護更新已達點到未達點的距離{if(!s[j] && dist[j] > Edge[v][j] + dist[v]){dist[j] = Edge[v][j] + dist[v];}}}printf("%d\n", dist[n]<INF?dist[n]:-1);}struct Node{int w;char begin[5], end[5];}a[1000+10];int main(){int i, j;freopen("a.txt", "r", stdin);while(~scanf("%d", &n) && n){char str[1000+10];for(i = 1; i<=n; i++){scanf("%d%s", &a[i].w, str);strncpy(a[i].begin, str, 4);a[i].begin[4] = '\0';strcpy(a[i].end, str+strlen(str) - 4);}memset(Edge, INF, sizeof(Edge));for(i = 1; i<=n; i++){for(j = 1; j<=n; j++){if(strcmp(a[i].end, a[j].begin) == 0){Edge[i][j] = a[i].w;}}}Dijkstra();}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.