跳到正文

题解

题解:P15818 [JOI 2015 Final] JOI 公园 / JOI Park

QQQhz508约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年5月4日
收录
2026年6月26日
更新
2026年11月18日
篇幅
约 5 分钟
获赞
6
题目
P15818

版本

  1. v1当前

题目大意

给定一个无向图和一个常数 cc,让你找到一个 xx,把到 11 的距离小于等于 xx 的点之间连接的边去掉,求 c×xc \times x 与剩余边权的和的最小值。

题目分析

既然要求距离,我们先以 11 为源点跑一遍 Dijkstra,求出距离之后给这些距离排序,然后遍历每个点,把 xx 设为当前点到 11 的距离,接下来就是去掉边的步骤。

那么怎么去掉边呢?我们先维护一个变量 sum,计算所有边权的总和,同时开一个标记数组,把到 11 的距离小于等于 xx 的点标为 true,接着对于每条边,假如它两个端点在标记数组中的值都是 true,那么就让 sum 的值减去这个边权。

最后用 c×x+sumc \times x + \texttt{sum} 更新答案。

总时间复杂度:Dijkstra O((n+m)log⁡n)O((n+m)\log n),排序 O(nlog⁡n)O(n \log n),枚举并检查每条边 O(m)O(m),整体 O((n+m)log⁡n+m)O((n+m)\log n + m),可以通过。

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
#define file_in(s) freopen(s".in","r",stdin);
#define file_out(s) freopen(s".out","w",stdout);
#define file(s) file_in(s) file_out(s)
#define sz(x) ((int)(x).size())
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
using ll=long long;
using ull=unsigned long long;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using pli=pair<ll,int>;
using tiii=tuple<int,int,int>;
using tlii=tuple<ll,int,int>;
using tlli=tuple<ll,ll,int>;
template<typename T,typename Compare=less<T>>
using heap=priority_queue<T,vector<T>,Compare>;
const int INF=0x3f3f3f3f;
const ll INFLL=0x3f3f3f3f3f3f3f3fLL;
const int MOD=1e9+7;
const double EPS=1e-8;
const int N=1e5+5;
struct square
{
	int id;
	ll dis;
}a[N];
struct edge
{
	int to,next;
	ll w;
}e[N<<2];
int n,m,cnt=0,head[N];
ll c,sum=0,ans=INFLL,d[N];
bool vhash[N];
inline void addedge(int u,int v,ll w)
{
	e[++cnt]=(edge){v,head[u],w};
	head[u]=cnt;
}
void dijkstra()
{
	heap<pli,greater<pli>> Q;
	Q.push(mp(0,1));
	d[1]=0;
	while(!Q.empty())
	{
		auto[cd,u]=Q.top();
		Q.pop();
		if(cd>d[u]) continue;
		for(int i=head[u];~i;i=e[i].next)
		{
			int v=e[i].to;
			ll w=e[i].w;
			if(d[v]>d[u]+w)
			{
				d[v]=d[u]+w;
				Q.push(mp(d[v],v));
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	memset(head,-1,sizeof(head));
	memset(d,INFLL,sizeof(d));
	cin>>n>>m>>c;
	for(int i=1,u,v;i<=m;i++)
	{
		ll w;
		cin>>u>>v>>w;
		sum+=w;//计算边权总和
		addedge(u,v,w);
		addedge(v,u,w);
	}
	dijkstra();//跑最短路
	for(int i=1;i<=n;i++) a[i]={i,d[i]};
	sort(a+1,a+n+1,[](square x,square y){return x.dis<y.dis;});//根据距离排序
	for(int i=1;i<=n;i++)
	{
		int u=a[i].id;//一定要用 a[i].id,不要用成 i 了
		ll dis=a[i].dis;
		vhash[u]=true;//标记该点
		for(int j=head[u];~j;j=e[j].next)
		{
			int v=e[j].to;
			ll w=e[j].w;
			if(vhash[v]) sum-=w;//假如边两个端点都被标记过了,就用 sum 减去边权
		}
		ans=min(ans,sum+c*dis);//更新答案
	}
	cout<<ans;
	return 0;
}