标题:记 CSP-S2 2025 T2 wssb. 赛时写出了如下暴力(已移除注释):
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=1e4+5,M=1e6+5,K=10+5,E=2e6+5,P=2e4+5;
int n,m,k,c[N],a[K][N],fa[P];
struct node{
int u,v,w;
}e[M],ne[E],tmp[E];
int find(int x){
if(x==fa[x]){
return x;
}
return fa[x]=find(fa[x]);
}
void add(int x,int y){
x=find(x);
y=find(y);
if(x!=y){
fa[x]=y;
}
return;
}
void ms(int a,int b){
int p1=1,p2=a+1;
for(int i=1;i<=b;i++){
if(p2>b||(p1<=a&&e[p1].w<=ne[p2].w)){
tmp[i]=e[p1];
p1++;
}
else{
tmp[i]=ne[p2];
p2++;
}
}
for(int i=1;i<=b;i++){
ne[i]=tmp[i];
}
return;
}
signed main(){
// freopen("road.in","r",stdin);
// freopen("road.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m>>k;
for(int i=1;i<=m;i++){
cin>>e[i].u>>e[i].v>>e[i].w;
ne[i]=e[i];
}
for(int i=0;i<k;i++){
cin>>c[i];
for(int j=1;j<=n;j++){
cin>>a[i][j];
}
}
int mini=1e18;
sort(e+1,e+1+m,[](node a,node b){
return a.w<b.w;
});
for(int i=0;i<(1<<k);i++){
int rc=m,ans=0;
for(int j=0;j<k;j++){
if((i>>j)&1){
for(int l=1;l<=n;l++){
ne[++rc]={n+j+1,l,a[j][l]};
}
ans+=c[j];
}
}
sort(ne+1+m,ne+1+rc,[](node a,node b){
return a.w<b.w;
});
ms(m,rc);
for(int j=1;j<=n+k;j++){
fa[j]=j;
}
for(int j=1;j<=rc;j++){
if(find(ne[j].u)!=find(ne[j].v)){
ans+=ne[j].w;
add(ne[j].u,ne[j].v);
}
}
mini=min(mini,ans);
}
cout<<mini;
return 0;
}能拿 72 pts。 然而我在赛事并没有正确地计算其时间复杂度,导致我以为它拿不了多少分,并且把代码改为(已移除注释):
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=1e4+5,M=1e6+5,K=10+5,E=2e6+5,P=2e4+5;
int n,m,k,c[N],a[K][N],fa[P],t[K];
struct node{
int u,v,w;
}e[E],ne[E],tmp[E];
mt19937 rnd(time(NULL)^random_device{}());
int find(int x){
if(x==fa[x]){
return x;
}
return fa[x]=find(fa[x]);
}
void add(int x,int y){
x=find(x);
y=find(y);
if(x!=y){
fa[x]=y;
}
return;
}
int kru(node t[],int tl){
sort(t+1,t+1+tl,[](node a,node b){
return a.w<b.w;
});
for(int i=1;i<=n+k;i++){
fa[i]=i;
}
int ans=0,cnt=0;
for(int i=1;i<=tl;i++){
if(find(t[i].u)!=find(t[i].v)){
ans+=t[i].w;
add(t[i].u,t[i].v);
tmp[++cnt]=t[i];
}
}
return ans;
}
signed main(){
// freopen("road.in","r",stdin);
// freopen("road.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m>>k;
for(int i=1;i<=m;i++){
cin>>e[i].u>>e[i].v>>e[i].w;
}
for(int i=1;i<=k;i++){
cin>>c[i];
for(int j=1;j<=n;j++){
cin>>a[i][j];
}
}
int ans=kru(e,m),cnt=n-1,sum=0;
for(int i=1;i<=cnt;i++){
e[i]=tmp[i];
}
for(int i=1;i<=k;i++){
t[i]=i;
}
shuffle(t+1,t+1+k,rnd);
for(int idx=1;idx<=k;idx++){
int i=t[idx];
for(int j=1;j<=cnt;j++){
ne[j]=e[j];
}
for(int j=1;j<=n;j++){
ne[j+cnt]={n+i,j,a[i][j]};
}
int t=kru(ne,cnt+n);
if(t+c[i]<ans){
ans=c[i];
sum+=t;
cnt++;
for(int j=1;j<=cnt;j++){
e[j]=tmp[j];
}
}
}
cout<<ans+sum;
return 0;
}