【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;
}
posted @ 2019-01-02 19:27  ywwyww  阅读(313)  评论(0编辑  收藏  举报