hdu 1142 A Walk Through the Forest(最短路)

来源:互联网 发布:java电商项目简历 编辑:程序博客网 时间:2024/05/17 20:13

给一个无向图,求满足要求的最短路条数。

能够从a到达b,当且仅当从a出发到达终点的最短路大于从b出发到达终点的最短路。


以终点为起点,起点为终点跑一遍最短路,求出各个顶点到终点的最短路。然后根据条件进行dfs即可求出答案。


#include<iostream>#include<cstdio>#include<cmath>#include<map>#include<set>#include<algorithm>#include<queue>#include<stack>#include<cstdlib>#include<cstring>#include<vector>#pragma comment(linker, "/STACK:1024000000,1024000000")using namespace std;typedef long long LL;typedef unsigned long long uLL;typedef __int64 LI;typedef unsigned __int64 uLI;typedef unsigned int uI;typedef double db;#define maxn 1005#define inf 0x3f3f3f3fstruct e{    int to,w,next;}edge[3000005];int cnt,head[maxn],s,t,n;inline void add(int u,int v,int w){    edge[cnt].to=v;    edge[cnt].w=w;    edge[cnt].next=head[u];    head[u]=cnt++;}bool vis[maxn];int low[maxn];void spfa(){    int i;    memset(vis,0,sizeof(vis));    memset(low,inf,sizeof(low));    low[2]=0;    vis[2]=1;    queue<int> q;    q.push(2);    while(!q.empty())    {        int u=q.front();q.pop();        vis[u]=0;        for(i=head[u]; ~i; i=edge[i].next)        {            int v=edge[i].to;            if(low[v]>low[u]+edge[i].w)            {                low[v]=low[u]+edge[i].w;                if(!vis[v])                {                    vis[v]=1;                    q.push(v);                }            }        }    }}int dp[maxn];int dfs(int u){    if(dp[u]) return dp[u];    for(int i=head[u];~i;i=edge[i].next)    {        int v=edge[i].to;        if(low[u]>low[v]) dp[u]+=dfs(v);    }    return dp[u];}int main(){    int n,m;    while(~scanf("%d",&n)&&n)    {        scanf("%d",&m);        cnt=0;        memset(head,-1,sizeof(head));        while(m--)        {            int a,b,c;            scanf("%d%d%d",&a,&b,&c);            add(a,b,c);            add(b,a,c);        }        spfa();        memset(dp,0,sizeof(dp));        dp[2]=1;        printf("%d\n",dfs(1));    }    return 0;}


0 0