hdu1598find the most comfortable road

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1598

题意:中文题。

分析:题目说点n=200实测好像有1000,因此RE了几次。原本的复杂度就有点大了,但是数据水。。思路就是先用并查集判能否达到终点,如果能到在去暴力枚举路径上的最小权值,然后只允许走大于最小权值的边,类似求最短一样求最小上界。O(q*m*nlogn)

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=1005;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=1000000007;
const int INF=1000000010;
const ll MAX=1ll<<55;
const double pi=acos(-1.0);
typedef double db;
typedef unsigned long long ull;
struct node {
    int x,y;
    node(){}
    node(int x,int y):x(x),y(y){}
    bool operator < (const node a) const {
        return x>a.x;
    }
};
priority_queue<node>Q;
int n,m,q[N],f[N],d[N],dis[N];
int tot,u[N],v[2*N],w[2*N],pre[2*N];
void add(int a,int b,int c) {
    v[tot]=b;w[tot]=c;pre[tot]=u[a];u[a]=tot++;
}
int find_f(int a) {
    return f[a]==a ? a:f[a]=find_f(f[a]);
}
void unio(int a,int b) {
    int fa=find_f(a),fb=find_f(b);
    if (fa!=fb) f[fa]=fb;
}
int getmin(int a,int b) {
    int i,j,k,ret=INF;
    node now;
    for (i=1;i<=m;i++) {
        for (j=1;j<=n;j++) q[j]=0,dis[j]=INF;
        dis[a]=d[i];Q.push(node(d[i],a));
        while (!Q.empty()) {
            now=Q.top();Q.pop();
            if (q[now.y]||now.x-d[i]>ret) continue ;
            q[now.y]=1;
            for (k=u[now.y];k!=-1;k=pre[k])
            if (!q[v[k]]&&w[k]>=d[i]&&max(now.x,w[k])<dis[v[k]]) {
                dis[v[k]]=max(now.x,w[k]);Q.push(node(dis[v[k]],v[k]));
            }
        }
        ret=min(ret,dis[b]-d[i]);
    }
    return ret;
}
int main()
{
    int a,b,i,q,fa,fb;
    while (scanf("%d%d", &n, &m)!=EOF) {
        for (tot=0,i=1;i<=n;i++) f[i]=i,u[i]=-1;
        for (i=1;i<=m;i++) {
            scanf("%d%d%d", &a, &b, &d[i]);
            add(a,b,d[i]);add(b,a,d[i]);unio(a,b);
        }
        scanf("%d", &q);
        while (q--) {
            scanf("%d%d", &a, &b);
            fa=find_f(a);fb=find_f(b);
            if (fa!=fb) printf("-1\n");
            else printf("%d\n", getmin(a,b));
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值