uva1395
Posted 033000-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uva1395相关的知识,希望对你有一定的参考价值。
题意见紫书
将边排序后取一段连续区间套用最小生成树模板即可,注意需要计数是否所有节点都被包含在内
#include<iostream> #include<cmath> #include<cstdio> #include<cstdlib> #include<cstring> #include<iomanip> #include<assert.h> #include<ctime> #include<vector> #include<list> #include<map> #include<set> #include<sstream> #include<stack> #include<queue> #include<string> #include<bitset> #include<algorithm> using namespace std; #define me(s) memset(s,0,sizeof(s)) #define _for(i,a,b) for(int i=(a);i<(b);++i) #define _rep(i,a,b) for(int i=(a);i<=(b);++i) #define mp make_pair #define pb push_back #define all(x) (x).begin(),(x).end() #define F first #define S second #define pf printf #define sf scanf #define Di(x) int x;scanf("%d",&x) #define in(x) inp(x) #define in2(x,y) inp(x),inp(y) #define in3(x,y,z) inp(x),inp(y),inp(z) #define ins(x) scanf("%s",x) #define ind(x) scanf("%lf",&x) #define IO ios_base::sync_with_stdio(0);cin.tie(0) #define READ freopen("C:/Users/ASUS/Desktop/in.txt","r",stdin) #define WRITE freopen("C:/Users/ASUS/Desktop/out.txt","w",stdout) template<class T> void inp(T &x) {//读入优化 char c = getchar(); x = 0; for (; (c < 48 || c>57); c = getchar()); for (; c > 47 && c < 58; c = getchar()) { x = (x << 1) + (x << 3) + c - 48; } } typedef pair <int, int> pii; typedef long long ll; typedef unsigned long long ull; const int inf = 0x3f3f3f3f; const int mod = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-15; const int maxn=10000+5; int u[maxn],v[maxn],w[maxn],f[maxn],r[maxn]; int n,m;//节点数和边数 //边的端点和权值分别存在u,v,w中 int cmp(const int &i,const int &j) {return w[i]<w[j];} //间接排序函数 int find(int x) {return f[x]==x?x:f[x]=find(f[x]);}//并查集 int Krusal(int x,int y){ int ans=0; for(int i=1;i<=n;i++) f[i]=i;//初始化并查集 int cnt=1; for(int i=x;i<=y;i++){ int e=r[i]; int x=find(u[e]),y=find(v[e]); if(x!=y) { ans+=w[e]; f[x]=y; cnt++; } } if(cnt==n) return w[r[y]]-w[r[x]]; else return inf; } int Solve(){ for(int i=0;i<m;i++) r[i]=i; sort(r,r+m,cmp); int ans=inf; _for(i,0,m){ _for(j,i,m){ if(w[r[j]]-w[r[i]]>=ans) continue; else ans=min(ans,Krusal(i,j)); } } return ans==inf?-1:ans; } int main(){ //READ; //WRITE; while(scanf("%d%d",&n,&m)==2,n){ _for(i,0,m) { in3(u[i],v[i],w[i]); } pf("%d ",Solve()); } }
以上是关于uva1395的主要内容,如果未能解决你的问题,请参考以下文章