【XSY3370】道路建设 最短路

题目大意

  有一个完全图,边有边权。

  对于每个 \(i\),求一棵生成树,使得( \(\sum_{j=1,j\neq i}^n\) \(j\)\(i\) 的路径上边权最小值) 最小。

  \(n\leq 2000,W\leq {10}^9\)

题解

  记最小的边权 \(w\),这条边的一个端点为 \(s\)

  那么 \(i\) 号点对应的生成树就是从 \(i\)\(s\) 的一条路径,然后经过边权最小的边,再连向所有点。

  可以发现 \(i\)\(s\) 的路径上除了最后一条边之外的边权是递减的。而且每条边的边权 \(<\) 后面所有边(除了最后一条边)的边权和。所以深度会 \(\leq O(\log W)\)

  直接从每个点开始跑最短路就可以做到 \(O(n^2\log W)\)

  从 \(s\) 开始向每个点跑最短路就可以在 \(O(n^2)\) 内解决这道题了。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<functional>
#include<cmath>
#include<vector>
#include<assert.h>
//using namespace std;
using std::min;
using std::max;
using std::swap;
using std::sort;
using std::reverse;
using std::random_shuffle;
using std::lower_bound;
using std::upper_bound;
using std::unique;
using std::vector;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef std::pair<int,int> pii;
typedef std::pair<ll,ll> pll;
void open(const char *s){
#ifndef ONLINE_JUDGE
    char str[100];sprintf(str,"%s.in",s);freopen(str,"r",stdin);sprintf(str,"%s.out",s);freopen(str,"w",stdout);
#endif
}
void open2(const char *s){
#ifdef DEBUG
    char str[100];sprintf(str,"%s.in",s);freopen(str,"r",stdin);sprintf(str,"%s.out",s);freopen(str,"w",stdout);
#endif
}
int rd(){int s=0,c,b=0;while(((c=getchar())<'0'||c>'9')&&c!='-');if(c=='-'){c=getchar();b=1;}do{s=s*10+c-'0';}while((c=getchar())>='0'&&c<='9');return b?-s:s;}
void put(int x){if(!x){putchar('0');return;}static int c[20];int t=0;while(x){c[++t]=x%10;x/=10;}while(t)putchar(c[t--]+'0');}
int upmin(int &a,int b){if(b<a){a=b;return 1;}return 0;}
int upmax(int &a,int b){if(b>a){a=b;return 1;}return 0;}
const int N=2010;
int a[N][N];
int b[N];
ll s[N];
int n;
int mi[N];
int main()
{
    open("a");
    n=rd();
    int w=0x7fffffff,t;
    for(int i=1;i<=n;i++)
        for(int j=i+1;j<=n;j++)
            a[i][j]=a[j][i]=rd();
    for(int i=1;i<=n;i++)
        mi[i]=0x7fffffff;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(j!=i)
                mi[i]=min(mi[i],a[i][j]);
    for(int i=1;i<=n;i++)
        if(mi[i]<w)
        {
            w=mi[i];
            t=i;
        }
    b[t]=1;
    s[t]=0;
    for(int i=1;i<=n;i++)
        if(i!=t)
            s[i]=min(a[t][i]-w,2*mi[i]-2*w);
    for(int i=1;i<n;i++)
    {
        int x=0;
        for(int j=1;j<=n;j++)
            if(!b[j]&&(!x||s[j]<s[x]))
                x=j;
        b[x]=1;
        for(int k=1;k<=n;k++)
            if(!b[k])
                s[k]=min(s[k],s[x]+a[x][k]-w);
    }
    for(int i=1;i<=n;i++)
        printf("%lld\n",s[i]+(ll)(n-1)*w);
    return 0;
}

转载于:https://www.cnblogs.com/ywwyww/p/10210685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值