HDU2433 Travel BFS求最短路徑樹+最佳化

來源:互聯網
上載者:User
/*1750ms邊長為1,所以用BFS求最短路對於每一個點,做一次BFS,求出以這個點為出發點時的最短路徑樹的長度和它包含的邊記錄長度是用於求值,記錄邊是用於最佳化。因為只有處於最短路徑樹上的邊的改動才會影響到結果如果要去的邊的不在最短路徑樹上,不影響結果,如果在,則重新計算最佳化後還是逾時,網上的解題報告都說用short,還是跑了1750ms,可能這題用vector來儲存不太合適*/#include <iostream>#include <vector>#include <queue>using namespace std;#define MAX 105struct node{short start;short end;}E[3005];vector<vector<int> >V(MAX);short dis[MAX], vis[MAX];bool hash[MAX][3005];void BFS(short start, short edge);int main(){short n, m, i, j, k, a, b, ans, temp;bool flag;while(scanf("%hd%hd",&n,&m)!=EOF){flag = 1;for(i = 0; i <= n; i++)V[i].clear();memset(dis, 0, sizeof(dis));memset(hash, 0, sizeof(hash));for(i = 0; i < m; i++){scanf("%hd%hd",&a,&b);E[i].start = a;E[i].end = b;V[a].push_back(i);V[b].push_back(i);}for(i = 1; i <= n; i++){if(!flag)break;BFS(i, -1);if(i == 1){for(j = 1; j <= n; j++){if(vis[j] == 0){flag = 0;break;}}}for(j = 1; j <= n; j++)dis[i] = dis[i] + vis[j] - 1;}for(i = 0; i < m; i++){if(flag == 0){printf("INF\n");continue;}ans = 0;for(j = 1; j <= n; j++){if(ans == -1)break;if(hash[j][i] == 0)ans = ans + dis[j];else{temp = 0;BFS(j, i);for(k = 1; k <= n; k++){if(temp == -1)break;if(vis[k] == 0)temp = -1;else temp = temp + vis[k] - 1;}if(temp == -1)ans = -1;else ans = ans + temp;}}if(ans == -1)printf("INF\n");elseprintf("%hd\n",ans);}}return 0;}void BFS(short start,short edge){memset(vis, 0, sizeof(vis));int p, q, i;queue<int> Q;vis[start] = 1;Q.push(start);while(!Q.empty()){p = Q.front();Q.pop();for(i = 0; i < V[p].size(); i++){q = E[V[p][i]].start + E[V[p][i]].end - p;if(vis[q])continue;//if(edge!=-1 && ((E[edge].start==p&&E[edge].end==q)||(E[edge].start==q&&E[edge].end==p)))if(edge == V[p][i])continue;if(edge == -1)hash[start][V[p][i]] = 1;vis[q] = vis[p] + 1;Q.push(q);}}}

聯繫我們

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