CNMIOS @ 2024-08-14 17:49:27
这是我的最小生成树代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int next,to,w;
}edge[200005<<1];
int n,m,cnt,head[5005],dis[5005],vis[5005],ans,num,now=1;
void addedge(int u,int v,int w){
edge[++cnt].next=head[u];
edge[cnt].to=v;
edge[cnt].w=w;
head[u]=cnt;
}
void prim(){
for(int i=2;i<=n;++i){
dis[i]=2147483647;
}
for(int i=head[1];i;i=edge[i].next){
dis[edge[i].to]=min(dis[edge[i].to],edge[i].w);
}
while(++num<n){
int minn=2147483647;
vis[now]=1;
for(int i=1;i<=n;i++){
if(!vis[i]&&minn>dis[i]){
minn=dis[i];
now=i;
}
}
ans+=minn;
for(int i=head[now];i;i=edge[i].next){
int v=edge[i].to;
if(dis[v]>edge[i].w && !vis[v]){
dis[v]=edge[i].w;
}
}
}
}
int main(){
cin >> n >> m;
for(int i=1;i<=m;i++){
int a,b,c;
cin >> a >> b >> c;
addedge(a,b,c);
addedge(b,a,c);
}
prim();
if(num<n)cout << "orz";
else cout << ans;
return 0;
}
84分,无解没判对,这是机房大巨给我条的AC代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int next,to,w;
}edge[200005<<1];
int n,m,cnt,head[5005],dis[5005],vis[5005],ans,num,now=1,wwe=1;
void addedge(int u,int v,int w){
edge[++cnt].next=head[u];
edge[cnt].to=v;
edge[cnt].w=w;
head[u]=cnt;
}
void prim(){
for(int i=2;i<=n;++i){
dis[i]=2147483647;
}
for(int i=head[1];i;i=edge[i].next){
dis[edge[i].to]=min(dis[edge[i].to],edge[i].w);
}
while(++num<n){
int minn=2147483647;
if(!vis[now]){wwe++;}
vis[now]=1;
for(int i=1;i<=n;i++){
if(!vis[i]&&minn>dis[i]){
minn=dis[i];
now=i;
}
}
ans+=minn;
for(int i=head[now];i;i=edge[i].next){
int v=edge[i].to;
if(dis[v]>edge[i].w && !vis[v]){
dis[v]=edge[i].w;
}
}
}
}
int main(){
cin >> n >> m;
for(int i=1;i<=m;i++){
int a,b,c;
cin >> a >> b >> c;
addedge(a,b,c);
addedge(b,a,c);
}
prim();
if(wwe < n){
cout << "orz";
}
else cout << ans;
return 0;
}
为什么又加了一个计数器就A了