HDU1142

来源:互联网 发布:数据库编程培训 编辑:程序博客网 时间:2024/06/05 12:44

        WA了好久,感觉WA率都因我而升。用了bellmon,dijkstra,以及dijkstra优化(偷偷说一下dijkstra到现在才会拼写),还没有使出必杀技SPFA.想了好久才知道原来源顶点为目的地,即2,一开始总以为要求起点 1 到其他所有点的最短路。原来理解错了——应为终点 2 到各点的最短路。

      

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <vector>#include <queue>#define INF 1000000007#define maxn 1005using namespace std;struct edge{   int to;   int cost;};typedef pair<int,int> P;int n;vector<edge>G[maxn];//int cost[maxn][maxn];int d[maxn];int path[maxn];int map1[maxn][maxn];bool used[maxn];void dijkstra(int s)             //最普通的dijkstra的打法。。{   fill(d, d+n+2,INF);   fill(used,used+n+2,false);   d[s] = 0;      while(true)   {      int v = -1;      for(int u = 1; u <= n; u ++)      {         if(!used[u] && (v == -1 || d[u]<d[v]))v = u;      }            if(v == -1)break;      used[v] = true;            for(int u = 1;u <= n; u ++)        d[u] = min(d[u], d[v] + map1[v][u]);   }}/*void dijkstra(int s){    priority_queue< P,vector<P>,greater<P> > que;    fill(d,d+n+2,INF);    d[s] = 0;    que.push(P(0,s));        while(!que.empty())    {        P p = que.top();que.pop();        int v = p.second;        if(d[v] < p.first)continue;        for(int i = 0;i < G[v].size(); i++)        {           edge e = G[v][i];           if(d[e.to] > d[v] + e.cost)           {              d[e.to] = d[v] + e.cost;              que.push(P(d[e.to],e.to));           }        }    }}*/int DFS(int s)                               //DFS搜索回溯。。{    if(path[s]!= -1)return path[s];                     if(s == 2)return 1;        path[s] = 0;    for(int i = 1; i <= n; i ++)    {        if(d[i] < d[s] && map1[i][s] != INF)        {           path[s] += DFS(i);        }    }    return path[s];}int main(){    while(~scanf("%d",&n),n)    {        int m;        int a,b,c;        scanf("%d",&m);        for(int i = 0; i <= n; i ++)        {           for(int j = 0; j <= n; j ++)            map1[i][j] = INF;           map1[i][i] = 0;        }        //memset(map1,INF,sizeof(map1));        for(int i = 0; i < m; i ++)           {              scanf("%d%d%d",&a,&b,&c);              /*edge y ;              y.to = b;              y.cost = c;              //G[a].push_back(y);              y.to = a;              G[b].push_back(y);*/              map1[a][b] = map1[b][a] = c;        }                dijkstra(2);           //最短路理解又加深了。。我在WA中艰难前进。。        //printf("%d\n",d[1]);        memset(path,-1,sizeof(path));        printf("%d\n",DFS(1));    }    return 0;}

0 0
原创粉丝点击