上海交通大學複試題 最短路徑

上海交通大學複試題 最短路徑

時間限制:1秒 空間限制:65536K 熱度指數:3277
算法知識視頻講解
校招時部分企業筆試將禁止編程題跳出頁面,爲提前適應,練習時請使用在線自測,而非本地IDE。

題目描述

N個城市,標號從0到N-1,M條道路,第K條道路(K從0開始)的長度爲2^K,求編號爲0的城市到其他城市的最短距離

輸入描述:

第一行兩個正整數N(2<=N<=100)M(M<=500),表示有N個城市,M條道路
接下來M行兩個整數,表示相連的兩個城市的編號

輸出描述:

N-1行,表示0號城市到其他城市的最短路,如果無法到達,輸出-1,數值太大的以MOD 100000 的結果輸出。
示例1

輸入

複製
4 4
1 2
2 3
1 3
0 1

輸出

複製
8
9
11

思路

這道題看似是一道常見的最短路的題目,但是邊權非常大,如果要寫成高精度可能會非常麻煩。但是如果模擬一遍就可以發現一些有用的細節。
如果按照以下的順序讀入邊:

e1 e1
e2 e3
e3 e1

那麼是否這三條邊都是有用的呢?答案是否定的,因爲第i行輸入邊權是2(i-1)由二進制的知識可以知道,此前的所有邊權都加起來也不會超過這個權值,也就是說如果這兩個節點已經在此前構建的某一個連通圖中,那麼當前輸入的邊權就一定可以捨去。那麼此時問題就退化成了構建一個MST的問題。顯然此時使用並查集構建一個MST,再套一個Dijkstra的殼就可以了。

#include <iostream>
#include <queue>
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <string>
#include <cstdlib>
#include <stack>
#include <vector>
#include <math.h>
#include <algorithm>
#include <typeinfo>
#include <cstring>


using namespace std;
typedef long long ll;

const ll inf = 1061109567;
const int maxn = 102;
const ll mod = 100000;


ll fpow(ll base,int exp){
	ll ans=1;
	while(exp){
		if(exp&1)	 ans=(ans*base)%mod;
		base=(base*base)%mod;
		exp>>=1;
	}
	return ans;
}

int root[maxn];
ll mat[maxn][maxn];

int find_root(int x){
	if(root[x]==-1)
		return x;
	else
		return find_root(root[x]);
}

int main(int argc, char const *argv[])
{
	int n,m;
	while(cin>>n>>m){
		for(int i=0;i<n;i++)
			root[i]=-1;

		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				mat[i][j]=inf;
			}
			mat[i][i]=0;
		}
		int a,b;
		ll w;
		for(int i=0;i<m;i++){
			cin>>a>>b;
			int ra=find_root(a);
			int rb=find_root(b);
			w = fpow(2,i);
			if(ra!=rb){
				root[rb]=ra;
				mat[a][b]=w;
				mat[b][a]=w;
			}
		}

		/*for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				if(mat[i][j]==inf)	cout<<"inf ";
				else cout<<mat[i][j]<<" ";
			}cout<<endl;
		}*/
		
		int s[maxn];
		ll dis[maxn];
		for(int i=0;i<n;i++){
			s[i]=0;
			dis[i]=mat[0][i];
		}
		s[0]=1;

		for(int i=1;i<n;i++){
			int u;
			for(int j=0;j<n;j++){
				if(!s[j]&&dis[j]!=inf)
					u=j;
			}
			s[u]=1;
			for(int j=0;j<n;j++){
				if(!s[j]&&mat[u][j]!=inf){
					dis[j]=(dis[u]+mat[u][j])%mod;
				}
			}
		}

		for(int i=1;i<n;i++){
			if(dis[i]==inf)	cout<<"-1"<<endl;
			else cout<<dis[i]<<endl;
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章