所有评测用例保证在所有候选隧道都修通时1号枢纽可以通过隧道到达其他所有枢纽。
这道题涉及到了最小生成树和并查集判断图的连通性。因为数量太大,所以不能用二维数组存下,要用vector数组,对vector有很多方法都不熟悉,借此了解一下。
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct edge{ int start,end,cost; bool operator<(const edge &n)const{ if(cost<n.cost)return true; return false; } }; int p[100010]; int Find(int x){ if(p[x]==x){ return x; } else{ int y=Find(p[x]); p[x]=y; return y; } } vector<struct edge> v;//struct型定义vector数组 int main(){ int n,m; scanf("%d%d",&n,&m); int a,b,c; edge nn; for(int i=0;i<=n;i++){ p[i]=i; } for(int i=0;i<m;i++){ scanf("%d%d%d",&a,&b,&c); nn.start=a; nn.end=b; nn.cost=c; v.push_back(nn); } sort(v.begin(),v.end());//vector数组的排序注意一下写法 int k=0; while(k<m){ int t1=v[k].start; int t2=v[k].end; int x=Find(t1); int y=Find(t2); if(x!=y){ p[x]=y; } if(Find(1)==Find(n)){ printf("%d",v[k].cost); break; } k++; } return 0; }