码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 3946 Highway Project

时间:2016-04-25 15:04:54      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

迪杰斯特拉最小堆

#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;

const long long INF=9999999999999;
const int maxn=2e5+10;
struct X{
    int id;
    long long time,cost;
    bool operator < (const X &a) const
    {
        if(time==a.time) return cost>a.cost;
        return time>a.time;
    }
    X(int f,long long g,long long h)
    {
        id=f,time=g,cost=h;
    }
};

struct Edge
{
    int from,to;
    long long time,cost;
    int next;
}s[maxn];
int head[maxn];
bool flag[maxn];
long long ans1,ans2;
long long dis[maxn];

int main()
{
    int T,n,m; scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);

        memset(head,-1,sizeof head);
        memset(flag,0,sizeof flag);
        ans1=ans2=0;
        for(int i=0;i<=n;i++) dis[i]=INF;

        int cnt=0;
        for(int i=1;i<=m;i++)
        {
            int u,v;
            long long time,cost;
            scanf("%d%d%lld%lld",&u,&v,&time,&cost);

            s[cnt].from=u,s[cnt].to=v,s[cnt].time=time,s[cnt].cost=cost;
            s[cnt].next=head[u],head[u]=cnt++;

            s[cnt].from=v,s[cnt].to=u,s[cnt].time=time,s[cnt].cost=cost;
            s[cnt].next=head[v],head[v]=cnt++;
        }

        priority_queue<X>q;
        q.push(X(0,0,0));  dis[0]=0;

        while(!q.empty())
        {
            X h=q.top(); q.pop();
            if(flag[h.id]==1) continue;

            flag[h.id]=1; ans1=ans1+h.time; ans2=ans2+h.cost;

            for(int i=head[h.id];i!=-1;i=s[i].next)
            {
                if(flag[s[i].to]==0&&dis[s[i].to]>=dis[h.id]+s[i].time)
                {
                    dis[s[i].to]=dis[h.id]+s[i].time;
                    q.push(X(s[i].to,dis[h.id]+s[i].time,s[i].cost));
                }
            }
        }
        printf("%lld %lld\n",ans1,ans2);
    }
    return 0;
}

 

ZOJ 3946 Highway Project

标签:

原文地址:http://www.cnblogs.com/zufezzt/p/5430775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!