【最小环 && 离散化】HDU 6005 Pandaland

来源:互联网 发布:redis hash key mysql 编辑:程序博客网 时间:2024/05/17 01:51

Problem Description

给你m条边,每条边给你两个城市的坐标,还有两个城市道路之间有成本
让你求一个最小成本的周期,至少包含三个城市。

思路:

因为只给了城市的坐标,我们得给每个城市对应一个编号,所以离散化。
因为题目给出边的个数,最大只有4000条。点的个数最大可以到达8000。
Floyd求最小环,肯定超时。枚举所有的边,求边的端点之间的最小成本。最小成本 + 边成本就是一个环成本。求最小的环成本。

#include<bits/stdc++.h>using namespace std;struct node{    int x, y;    bool operator < (const node &b) const {        if(x == b.x) return y < b.y;        else return x < b.x;    }    bool operator == (const node &b) const {        if(x == b.x && y == b.y) return 1;        else return 0;    }};struct Node{    int to, w, next;    bool operator < (const Node &b) const {        if(w == b.w) return to > b.to;        else return w > b.w;    }};#define inf 0x3f3f3f3f#define maxn 9000node a[2*maxn];Node Map[maxn];int dist[maxn], cnt, head[maxn], n;int ux[maxn], uy[maxn], vx[maxn], vy[maxn], w[maxn];int vv[maxn];int dij(int u, int v, int su)//dij + 优先队列{    priority_queue<Node> q;    memset(dist, inf, sizeof(dist));    dist[u] = 0;    q.push((Node){u, dist[u]});    while(!q.empty())    {        Node t = q.top(); q.pop();        u = t.to;        if(su <= dist[u]) return inf;//要找到的最短路 至少得比su小,不然ans没法更新        if(u == v) return dist[u];//求出最短路,直接返回        for(int i = head[u]; ~i; i = Map[i].next)        {            if(vv[i]) continue;            int to = Map[i].to, w = Map[i].w;            if(dist[to] > dist[u] + w)            {                dist[to] = dist[u] + w;                q.push((Node){to, dist[to]});            }        }    }    return inf;}void add(int u, int v, int w){    Map[cnt] = (Node){v, w, head[u]};    head[u] = cnt++;    Map[cnt] = (Node){u, w, head[v]};    head[v] = cnt++;}int main(){    int T, m, i, j, Case = 1;    scanf("%d", &T);    while(T--)    {        n = 1;        scanf("%d", &m);        cnt = 0;        memset(head, -1, sizeof(head));        for(i = 0; i < m; i++)        {            scanf("%d %d %d %d %d", &ux[i], &uy[i], &vx[i], &vy[i], &w[i]);            a[n++] = (node){ux[i], uy[i]};            a[n++] = (node){vx[i], vy[i]};        }        //离散化        sort(a+1, a+n);        n = unique(a+1, a+n) - a;        for(i = 0; i < m; i++)        {            int u = lower_bound(a+1, a+n, (node){ux[i], uy[i]}) - a;            int v = lower_bound(a+1, a+n, (node){vx[i], vy[i]}) - a;            add(u, v, w[i]);        }        int ans = inf;        memset(vv, 0, sizeof(vv));        for(i = 1; i <= n; i++)        {            for(j = head[i]; ~j; j = Map[j].next)            {                int to = Map[j].to, w = Map[j].w;                if(i > to) continue;//因为i->to的最短路 == to->i的最短路,所以没必要重复跑                vv[j] = 1;//标记该边不能走。                vv[j^1] = 1;                int k = dij(i, to, ans-w);//求i到to的最短距离                ans = min(ans, k + w);                vv[j] = 0;                vv[j^1] = 0;            }        }        if(ans == inf) ans = 0;        printf("Case #%d: %d\n", Case++, ans);    }    return 0;}
原创粉丝点击