题意:给你一个n个点m条边的无向图,每一条边都有一个权值,让你求出一个生成树,使得最大边减去最小边值最小。
思路:如果枚举每条边作为第一条边再求生成树,时间复杂度为O(m*m*logm),18S也不能接受,正确的思路是先求出最小生成树,然后在这个基础上加边,会形成一个环,然后删除这个环上的最小边,更新答案,这样的话时间复杂度会降到O(n*m)~~
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define bug puts("bug")
const int maxn = 400 + 10;
const int maxe = 80000 + 10;
struct Edge{
int u, v, d;
Edge(int u = 0, int v = 0, int d = 0) : u(u), v(v), d(d) {}
bool operator < (const Edge &rhs) const{
return d < rhs.d;
}
};
int n, m;
int pa[maxn];
int cur_min, cur_max;
int vis[maxe];
Edge edge[maxe];
int step;
Edge save[maxn];
vector<pair<int, int> > G[maxn];
vector<pair<int, int> >::iterator it;
void add(int u, int v, int d){
G[u].push_back(make_pair(v, d));
G[v].push_back(make_pair(u, d));
}
bool find_path(int fa, int u, int ed){
if(u == ed) return true;
for(int i = 0; i < (int)G[u].size(); i++){
int v = G[u][i].first;
int d = G[u][i].second;
if(v == fa) continue;
save[step++] = Edge(u, v, d);
if(find_path(u, v, ed)) return true;
step--;
}
return false;
}
void del(int x, int y){
for(it = G[x].begin(); it != G[x].end(); it++){
if((*it).first == y){
G[x].erase(it);
break;
}
}
}
void work(int u, int v, int d){
step = 0;
find_path(-1, u, v);
sort(save, save + step);
del(save[0].u, save[0].v);
del(save[0].v, save[0].u);
G[u].push_back(make_pair(v, d));
G[v].push_back(make_pair(u, d));
}
void update(int u, int fa){
for(int i = 0; i < (int)G[u].size(); i++){
int v = G[u][i].first;
if(v == fa) continue;
cur_min = min(cur_min, G[u][i].second);
cur_max = max(cur_max, G[u][i].second);
update(v, u);
}
}
int find_set(int x){
return pa[x] == x ? x : pa[x] = find_set(pa[x]);
}
int Kruscal(){
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; i++) pa[i] = i;
sort(edge, edge + m);
int ans, cnt = 0;
cur_min = edge[0].d, cur_max;
for(int i = 0; i < m; i++){
int x = find_set(edge[i].u);
int y = find_set(edge[i].v);
if(x != y){
pa[y] = x;
add(edge[i].u, edge[i].v, edge[i].d);
vis[i] = 1;
if(++cnt == n-1){
cur_max = edge[i].d;
ans = cur_max - cur_min;
break;
}
}
}
for(int i = 0; i < m; i++)if(!vis[i]){
work(edge[i].u, edge[i].v, edge[i].d);
cur_min = 1e9;
cur_max = 0;
update(0, -1);
ans = min(ans, cur_max - cur_min);
}
return ans;
}
void solve(){
scanf("%d", &m);
for(int i = 0; i < n; i++) G[i].clear();
for(int i = 0; i < m; i++){
int u, v, d;
scanf("%d%d%d", &u, &v, &d);
edge[i] = Edge(u, v, d);
}
printf("%d\n", Kruscal());
}
int main()
{
while(scanf("%d", &n) && n) solve();
return 0;
}