UVa208,Firetruck

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   資料   for   

要事先判斷結點1能否到達K,否則真的會逾時的= =(我一開始不信,感覺應該能正常退出dfs啊,結果真的逾時了)

我是判斷的k是否與其他結點有路,是的話才dfs(資料水,居然過了)

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <algorithm>#include <queue>#define maxn 20+5using namespace std;struct Node{    int x,y;};int map[maxn][maxn],k,d[maxn],vis[maxn],tot,m;int init(){    memset(map,0,sizeof(map));    memset(d,0,sizeof(d));    memset(vis,0,sizeof(vis));    tot=0;m=0;    int x,y;    while(cin>>x>>y&&x&&y)        {map[x][y]=1;map[y][x]=1;m=max(m,x);m=max(m,y);}}int printf(){    int ans[maxn],t=0,i;    i=k;tot++;    while (d[i]!=0){        t++;        ans[t]=d[i];        i=d[i];    }    for (i=t;i>=1;i--) cout<<ans[i]<<" ";    cout<<k;    cout<<endl;}int dfs(int i){    if (i==k) {printf();return 0;}    for (int j=1;j<=m;j++){        if (map[i][j]&&!vis[j]){            d[j]=i;            vis[j]=1;            dfs(j);            vis[j]=0;        }    }}int main(){    int ti=0;    while(cin>>k){        init();        ti++;        cout<<"CASE "<<ti<<":"<<endl;        int ok=0;        for (int i=1;i<=m;i++)            if (map[i][k]) ok=1;        vis[1]=1;        if (ok)dfs(1);        cout<<"There are "<<tot<<" routes from the firestation to streetcorner "<<k<<"."<<endl;    }}
View Code

 做出來一個題沒什麼,重要的是做完後的反思,尤其是像我這種水過的,My Code0.195s,嚴格來說還應該是TLE的代碼

然後去網上看別人的思路與想法結合自己的反思

直接copy原話:

裸搜會逾時的題目,其實題目的資料特地設計得讓圖稠密但起點和終點卻不相連,所以直接搜尋過去會逾時。

只要判斷下起點和終點能不能相連就行了,可以用並查集也可以用floyd演算法,這樣就能過了。

但是這個方法不是很完美的,如果兩點之間只有一條線相連,而圖又是稠密圖,這樣也很容易逾時,資料強電就會掛掉。

可以把演算法改進一下:是先從終點出發,無回溯的走遍和終點相連的所有點並標記,然後從起點出發,DFS判斷下標記,這樣就不會多走很多路了。另一個方法是在把點併入並查集的時候不考慮起點,然後DFS只走和終點同一集合的點。(這我聯想到了前面的文章倒著bfs標記所有能達到的點的最短距離,這裡n才20,用floyd遍曆就可以了)

某位大神的部落格上說Tarjan演算法也可以很好的實現。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.