标签:ssi field inpu 需要 建设 accept des other arc
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 35957 Accepted Submission(s): 15971
#include<iostream> #include<cstring> #include<algorithm> #include<string> #include<cmath> #define inf 0x3f3f3f3f using namespace std; int d[100005]; struct node { int v; int c; int nxt; }e[100005]; int head[100005]; int cnt=1; bool book[10005]; void add(int u,int v,int c) { e[cnt].c=c; e[cnt].v=v; e[cnt].nxt=head[u]; head[u]=cnt++; } int main() { int n,m; while(cin>>m>>n) { if(m==0) break; cnt=1; memset(d,inf,sizeof(d)); memset(head,-1,sizeof(head)); memset(book,0,sizeof(book)); for(int i=1;i<=m;i++) { int x,y,z; cin>>x>>y>>z; add(x,y,z); add(y,x,z); } for(int i=head[1];i!=-1;i=e[i].nxt) { if(d[e[i].v]>e[i].c) { d[e[i].v]=e[i].c; } } d[1]=0; book[1]=1; bool f=1; int sum=0; for(int i=1;i<=n-1;i++) { int k=-1; int min=inf; for(int j=1;j<=n;j++) { if(!book[j]&&min>d[j]) { min=d[j]; k=j; } } if(k==-1) { f=0; break; } book[k]=1; sum+=d[k]; for(int j=head[k];j!=-1;j=e[j].nxt ) { int x=e[j].v; int c=e[j].c; if(!book[x]&&d[x]>c) { d[x]=c; } } } if(!f) cout<<"?"<<endl; else cout<<sum<<endl; } return 0; }
kruskal
#include<iostream> #include<cstring> #include<algorithm> #include<string> #include<cmath> #define inf 0x3f3f3f3f using namespace std; int pra[100005]; struct node { int u,v,c; }e[100005]; bool cmp(node x,node y) { return x.c<y.c; } int find(int x) { if(pra[x]==x) return x; else return pra[x]=find(pra[x]); } void unite(int x,int y) { x=find(x); y=find(y); if(x==y) return; else { pra[x]=y; } } int main() { int n,m; while(cin>>m>>n) { if(m==0) break; for(int i=1;i<=n;i++) pra[i]=i; for(int i=1;i<=m;i++) { cin>>e[i].u>>e[i].v>>e[i].c; } sort(e+1,e+m+1,cmp); int sum=0; int k=0; for(int i=1;i<=m;i++) { int x=e[i].u;x=find(x); int y=e[i].v;y=find(y); if(x!=y) { unite(x,y); k++; sum+=e[i].c; } if(k==n-1) break; } if(k==n-1) cout<<sum<<endl; else cout<<"?"<<endl; } return 0; }
HDU 1863 畅通工程(Prim,Kruskal,邻接表模板)
标签:ssi field inpu 需要 建设 accept des other arc
原文地址:https://www.cnblogs.com/caiyishuai/p/8981651.html