Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

dij+手搓

Posted by ccl66 at 2017-11-26 16:54:34 on Problem 1511
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
#define MAX 1100000
using namespace std;
int head[MAX],top;
int dis[MAX],vis[MAX];
struct edge{
    int from;
    int to;
    int cost;
    int next;
}e[MAX],save[MAX];
void push_front(int from,int to,int cost)
{
    top++;
    e[top].from=from;
    e[top].to=to;
    e[top].cost=cost;
    e[top].next=head[from];
    head[from]=top;
}
struct Node{
    int x;
    int cost;
    bool operator<(const Node &b)const
    {

        return b.cost<cost;
    }
}temp,p,sta;
void bfs(int s)
{
    sta.x=s;
    sta.cost=0;
    memset(vis,0,sizeof(vis));
    memset(dis,0,sizeof(dis));
    priority_queue<Node> que;
    que.push(sta);
    while(!que.empty())
    {
        p=que.top();
        que.pop();
        if(!vis[p.x])
        {
            vis[p.x]=1;
            dis[p.x]=p.cost;
            for(int i=head[p.x];i!=0;i=e[i].next)
            {
                temp.x=e[i].to;
                if(!vis[temp.x])
                {
                    temp.cost=p.cost+e[i].cost;
                    que.push(temp);

                }
            }
        }
    }
   // printf("%d\n",dis[en]);
}
int main()
{
    int t,q,n;
    while(~scanf("%d",&t))
    {
        while(t--)
        {

            scanf("%d%d",&n,&q);
            for(int i=1; i<=q; i++)
            {
                int u,v,c;
                scanf("%d%d%d",&u,&v,&c);
                save[i].from=u,save[i].to=v,save[i].cost=c;
            }
            long long ans=0;
            ///1
            top=0;
            memset(head,0,sizeof(head));
            for(int i=1;i<=q;i++)
                push_front(save[i].from,save[i].to,save[i].cost);
            bfs(1);
            for(int i=1;i<=n;i++)ans+=dis[i];
            ///2
            top=0;
            memset(head,0,sizeof(head));
            for(int i=1;i<=q;i++)
                push_front(save[i].to,save[i].from,save[i].cost);
            bfs(1);
            for(int i=1;i<=n;i++)ans+=dis[i];

            ///
            printf("%lld\n",ans);


        }

    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator