题意
给出n个点m条边以及边的权值,求出点a到点b的一条路,这条路上所有边的最大值-最小值的值最小。这个题有两种做法:
1.二分+最短路:枚举差值和最小值。
2.并查集+Kruscal:排序后,枚举每一条边。
AC代码(第二种做法)
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
struct edge{
int u, v, c;
}node[1010];
int n, m, q;
int father[210];
bool cmp(const edge &A, const edge &B){
return A.c < B.c;
}
void init(){
for(int i=1; i<=n; i++)
father[i] = i;
}
int find(int x){
if(x != father[x])
father[x] = find(father[x]);
return father[x];
}
int main(){
while(scanf("%d%d",&n,&m) == 2){
for(int i=0; i<m; i++)
scanf("%d%d%d",&node[i].u, &node[i].v, &node[i].c);
sort(node, node+m, cmp);
scanf("%d",&q);
while(q--){
int s, e;
scanf("%d%d",&s, &e);
int ans = INF;
for(int i=0; i<m; i++){
init();
for(int j=i; j<m; j++){
int u = node[j].u, v = node[j].v;
int uu = find(u), vv = find(v);
if(uu != vv)
father[vv] = uu;
if(find(s) == find(e)){
ans = min(ans, node[j].c - node[i].c);
break;
}
}
}
if(ans == INF) puts("-1");
else printf("%d\n", ans);
}
}
return 0;
}
AC代码(方法1)
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 210;
const int M = 1010;
int n, m, q;
int dis[N], vis[N];
int tot, head[N],C[M];
struct edge{
int v, c, next;
}node[M << 1];
void init(){
tot = 0;
for(int i=1; i<=n; i++){
head[i] = -1;
}
}
void addedge(int u, int v, int c){
node[tot].v = v;
node[tot].c = c;
node[tot].next = head[u];
head[u] = tot++;
}
bool SPFA(int s, int e, int l, int r){
for(int i=1; i<=n; i++){
dis[i] = INF;
vis[i] = 0;
}
queue <int> Q;
Q.push(s);
vis[s] = 1, dis[s] = 0;
while(!Q.empty()){
s = Q.front();
Q.pop();
for(int i = head[s]; i!=-1; i=node[i].next){
int v = node[i].v;
int c = node[i].c;
if(c < l || c > r) continue;
if(dis[s] + c < dis[v]){
if(v == e) return true;
dis[v] = dis[s] + c;
if(!vis[v]){
vis[v] = 1;
Q.push(v);
}
}
}
}
return false;
}
int main(){
while(scanf("%d%d",&n, &m) == 2){
init();
int Max = -1;
for(int i=0; i<m; i++){
int u, v, c;
scanf("%d%d%d",&u, &v, &c);
Max = max(Max, c);
addedge(u, v, c);
addedge(v, u, c);
C[i] = c;
}
sort(C, C + m);
scanf("%d",&q);
while(q--){
int s, e;
scanf("%d%d",&s, &e);
int l = 0, r = Max;
int ans = -1;
while(l <= r){
int mid = (l + r) >> 1;
bool flag = false;
for(int i=0; C[i]+mid <= Max; i++){
if(SPFA(s, e, C[i], C[i]+mid)){
flag = true;
break;
}
}
if(flag) ans = mid, r= mid - 1;
else l = mid + 1;
}
printf("%d\n", ans);
}
}
return 0;
}