xdoj Problem 1047 - Let's SPFA

简介:

    一道很奸诈的水题

    奸诈之处在于如果是顺序存的一下就过了,但是如果是像用邻接表那样逆序的话,估计就只有TLE了……

 

下面给一个邻接表的顺序版……其实没必要

/*
author:jxy
lang:C/C++
university:China,Xidian University
**If you need to reprint,please indicate the source**
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#define INF 1E9
using namespace std;
#define Maxn 40010
#define Maxm 140010
int w[Maxm],u[Maxm],next[Maxm],cnt;
int first[Maxn],d[Maxn],last[Maxn];
int m,n;
bool in[Maxn];
queue<int> q;
void add(int vn,int un,int wn)
{
    if(first[vn]==-1)first[vn]=cnt;
    if(last[vn]!=-1) next[last[vn]]=cnt;
    last[vn]=cnt;
    next[cnt]=-1;
    u[cnt]=un;w[cnt]=wn;
    cnt++;
}
long long spfa()
{
    int i,now,ne,t,len,j;
    memset(in,0,sizeof(in));
    for(i=0;i<n;i++)d[i]=INF;
    d[0]=0;in[0]=1;q.push(0);
    while(!q.empty())
    {
        now=q.front();q.pop();
        in[now]=0;
        for(i=first[now];i!=-1;i=next[i])
        {
            ne=u[i];
            if(d[ne]<=(t=d[now]+w[i]))continue;
            d[ne]=t;
            if(in[ne])continue;
            in[ne]=1;q.push(ne);
        }

    }
    long long ans=0;
    for(i=1;i<n;i++) ans+=d[i];
    return ans;
}
int main()
{
    int v,u,w;
    while(~scanf("%d%d",&n,&m))
    {
        cnt=0;
        memset(first,-1,sizeof(first));
        memset(last,-1,sizeof(last));
        while(m--)
        {
            scanf("%d%d%d",&v,&u,&w);
            add(v,u,w);
            add(u,v,w);
        }
        printf("%lld\n",spfa());
    }
}


 

目录
相关文章
|
29天前
|
Java
HDU-2199-Can you solve this equation?
HDU-2199-Can you solve this equation?
21 0
|
29天前
|
Java
HDU-2199-Can you solve this equation
HDU-2199-Can you solve this equation
19 0
|
29天前
|
Java
hdu-1016-Prime Ring Problem
hdu-1016-Prime Ring Problem
14 0
|
1月前
G - Prime Ring Problem(深搜)
G - Prime Ring Problem(深搜)
|
7月前
|
图形学
hdu1086 You can Solve a Geometry Problem too(判断线段相交)
hdu1086 You can Solve a Geometry Problem too(判断线段相交)
34 0
|
8月前
|
开发框架 .NET
poj 3468 A Simple Problem with Integers线段树区间修改
题目意思很简单,有N个数,Q个操作, Q l r 表示查询从l到r 的和,C l r v 表示将从l到r 的值加上v,明显的线段树,不知道线段树的人肯定暴力,肯定超时,哈哈!!
22 0
HDOJ 1016 Prime Ring Problem素数环【深搜】
HDOJ 1016 Prime Ring Problem素数环【深搜】
97 0
HDOJ 1016 Prime Ring Problem素数环【深搜】
|
算法 Go
HDU-1548,A strange lift(Dijkstra)
HDU-1548,A strange lift(Dijkstra)
|
C语言
HDOJ 1016 Prime Ring Problem素数环【深搜2】
HDOJ 1016 Prime Ring Problem素数环【深搜】
84 0