夏夜、

心若平似镜、何题不AC。

UVA 10917 Walk Through the Forest 最短路 + DP

求出最短路后,如果d[A]<d[B] 则B可以走向A

是个DAG。

//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<sstream>
#include<cmath>
#include<climits>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
#define pb(a) push(a)
#define INF 0x1f1f1f1f
#define lson idx<<1,l,mid
#define rson idx<<1|1,mid+1,r
#define PI  3.1415926535898
template<class T> T min(const T& a,const T& b,const T& c) {
    return min(min(a,b),min(a,c));
}
template<class T> T max(const T& a,const T& b,const T& c) {
    return max(max(a,b),max(a,c));
}
void debug() {
#ifdef ONLINE_JUDGE
#else

    freopen("d:\\in1.txt","r",stdin);
    freopen("d:\\out1.txt","w",stdout);
#endif
}
int getch() {
    int ch;
    while((ch=getchar())!=EOF) {
        if(ch!=' '&&ch!='\n')return ch;
    }
    return EOF;
}

struct Edge
{
    int from,to,dist;
};
struct HeapNode
{
    int d,u;
    bool operator < (const HeapNode &ant ) const
    {
        return d>ant.d;
    }
};

const int maxn=1005;
int n;
vector<int> g[maxn];
vector<Edge> edge;

void InitGraph()
{
    for(int i=1;i<=n;i++)
        g[i].clear();
    edge.clear();
}

void AddEdge(int u,int v,int w)
{
    Edge e=(Edge){u,v,w};
    edge.push_back(e);
    g[u].push_back(edge.size()-1);
}

int done[maxn];
int d[maxn];

void Dijksta(int s)
{
    priority_queue<HeapNode> q;
    q.push((HeapNode){0,s});
    for(int i=1;i<=n;i++)
        d[i]=INF;
    d[s]=0;
    memset(done,0,sizeof(done));
    while(!q.empty())
    {
        HeapNode x=q.top();q.pop();
        if(done[x.u])continue;
        done[x.u]=1;
        for(int i=0;i<g[x.u].size();i++)
        {
            Edge &e=edge[g[x.u][i]];
            if(d[e.to]>d[x.u]+e.dist)
            {
                d[e.to]=d[x.u]+e.dist;
                q.push((HeapNode){d[e.to],e.to});
            }
        }
    }
}

int dp[maxn];
int f(int u)
{
    if(u==2)return 1;
    if(dp[u]>=0)return dp[u];
    dp[u]=0;
    for(int i=0;i<g[u].size();i++)
    {
        int v=edge[g[u][i]].to;
        if(d[v]<d[u])
            dp[u]+=f(v);
    }
    return dp[u];
}
int DP()
{
    memset(dp,-1,sizeof(dp));
    return f(1);
}

int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        InitGraph();
        int m;
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            AddEdge(u,v,w);
            AddEdge(v,u,w);
        }
        Dijksta(2);
        int res=DP();
        printf("%d\n",res);
    }
    return 0;
}
View Code

 

posted on 2014-03-29 19:18  BMan、  阅读(191)  评论(0编辑  收藏  举报

导航