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