P9327 [CCC 2023 S4] Minimum Cost Roads
考虑不存在重边的情况。
对于一对起点和终点
否则,令
抛开重边的情况来看,这道题的其实并不太是像最小化题目,选哪些边是确定的。
有重边判一下就好。
具体实现上,第一关键字为长度,第二关键字为价值升序排序。这样保证最先选到的是两个端点之间的最短路径。如果这两个点不连通则直接加入这条边,否则判断当前的最短路如果大于这条边的长度则加入(等于没有加入的必要,上一段说明了这一点)。
复杂度
Update:好像做法很多,排序的方式也很多。
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define maxn 2005
#define put() putchar('\n')
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
using namespace std;
void read(int &x){
int f=1;x=0;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();}
x*=f;
}
namespace Debug{
Tp void _debug(char* f,Ty t){cerr<<f<<'='<<t<<endl;}
Ts void _debug(char* f,Ty x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
Tp ostream& operator<<(ostream& os,vector<Ty>& V){os<<"[";for(auto& vv:V) os<<vv<<",";os<<"]";return os;}
#define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
#define fi first
#define se second
#define mk make_pair
const int mod=1e9+7;
int power(int x,int y=mod-2) {
int sum=1;
while (y) {
if (y&1) sum=sum*x%mod;
x=x*x%mod;y>>=1;
}
return sum;
}
priority_queue<pair<int,int> >q;
struct yyy {
int x,y,l,c;
}a[maxn];
int fa[maxn],ans,vis[maxn],dis[maxn],n,m;
int getfa(int x) {return x==fa[x]?x:fa[x]=getfa(fa[x]);}
bool cmp(yyy x,yyy y) {return x.l==y.l?x.c<y.c:x.l<y.l;}
vector<pair<int,int> >to[maxn];
const int inf=1e12;
bool check(int s,int t,int d) {
int i,x;
for (i=1;i<=n;i++) dis[i]=inf,vis[i]=0;
while (!q.empty()) q.pop();
q.push(mk(-(dis[s]=0),s));
while (!q.empty()) {
int x=q.top().se;q.pop();
if (vis[x]) continue;vis[x]=1;
for (auto tmp:to[x]) if (!vis[tmp.fi]&&dis[tmp.fi]>dis[x]+tmp.se) {
dis[tmp.fi]=dis[x]+tmp.se;
q.push(mk(-dis[tmp.fi],tmp.fi));
}
}
return d<dis[t];
}
signed main(void){
int i;
read(n);read(m);
for (i=1;i<=m;i++) {
read(a[i].x),read(a[i].y),read(a[i].l),read(a[i].c);
}
for (i=1;i<=n;i++) fa[i]=i;
sort(a+1,a+1+m,cmp);
for (i=1;i<=m;i++) {
auto tmp=a[i];
if (getfa(tmp.x)^getfa(tmp.y)) {
fa[getfa(tmp.x)]=getfa(tmp.y);
ans+=tmp.c;
to[a[i].x].push_back(mk(a[i].y,a[i].l));
to[a[i].y].push_back(mk(a[i].x,a[i].l));
}
else if (check(tmp.x,tmp.y,tmp.l)) {
ans+=tmp.c;
to[a[i].x].push_back(mk(a[i].y,a[i].l));
to[a[i].y].push_back(mk(a[i].x,a[i].l));
}
}
printf("%lld\n",ans);
return 0;
}