HDU 1535 Invitation Cards

来源:互联网 发布:nodejs 数据接口开发 编辑:程序博客网 时间:2024/05/17 02:01

转载请注明出处:http://blog.csdn.net/a1dark

分析:邻接表+双向spfa、注意答案要求int64、

#include<stdio.h>#define M 1000005#define INF 1000000009int mark[M],cost[M],head[M],head1[M],Q[M*10];int k,k1,st,ed,n,m;struct node{    int to,next,val;}a[M],b[M];void add(int x,int y,int v){    a[k].to=y;    a[k].val=v;    a[k].next=head[x];     head[x]=k++;}void spfa(){    int i,j,L,H;    int s,p;    L=H=0;    Q[H++]=st;    mark[st]=1;    cost[st]=0;    while(L<H)    {        p=Q[L++];        mark[p]=0;        for(i=head[p]; i!=-1; i=a[i].next)        {            s=a[i].to;            if(cost[s]-cost[p]>a[i].val)            {                cost[s]=cost[p]+a[i].val;                if(!mark[s])                {                    Q[H++]=s;                    mark[s]=1;                }            }        }    }}void add1(int x,int y,int v){    b[k1].to=y;    b[k1].val=v;    b[k1].next=head1[x];    head1[x]=k1++;}void spfa1(){    int i,j,L,H;    int s,p;    L=H=0;    Q[H++]=st;    mark[st]=1;    cost[st]=0;    while(L<H)    {        p=Q[L++];        mark[p]=0;        for(i=head1[p]; i!=-1; i=b[i].next)        {            s=b[i].to;            if(cost[s]-cost[p]>b[i].val)            {                cost[s]=cost[p]+b[i].val;                if(!mark[s])                {                    Q[H++]=s;                    mark[s]=1;                }            }        }    }}int main(){    int t,x,y,v;    int i,j;    __int64 sum;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        for(i=1;i<=n;i++)        {            head[i]=head1[i]=-1;            cost[i]=INF;            mark[i]=0;        }        k=k1=0;        for(i=0;i<m;i++)        {            scanf("%d%d%d",&x,&y,&v);            add(x,y,v);            add1(y,x,v);        }        sum=0;        st=1;        spfa();        for(i=2;i<=n;i++)            sum+=cost[i];        for(i=1;i<=n;i++)        {            cost[i]=INF;            mark[i]=0;        }        spfa1();        for(i=2;i<=n;i++)            sum+=cost[i];        printf("%I64d\n",sum);    }    return 0;}


原创粉丝点击