POJ 3255 Roadblocks

POJ 3255 Roadblocks
题目大意:给出n个顶点和m条边,求出顶点1到顶点n的次短路。次短路径允许一条边走多次。
很早就知道这个问题了,也很早就知道算法了,可是一直不知道为什么这么做是正确的,今天听了cw牛的讲解豁然开朗。
假设该问题要求的次短路经过边<u,v>,注意是有向边,那么d[1][u]+w(u,v)+d[v][n]就是经过这条边的最短路,如果这个值大于最短路的话,它就有可能成为次短路。因此,枚举次短路经过的边即可。
以下是我的代码:
#include < list >
#include
< queue >
#include
< algorithm >
#include
< cstdio >
#include
< cstring >
using   namespace  std;
const   int  kMaxn( 5007 );

struct  Type
{
    Type(
int  value1, int  value2):v(value1),w(value2) {}
    
int  v,w;
};

int  n,m,ans,d1[kMaxn],dn[kMaxn];
list
< Type >  g[kMaxn];

void  spfa( int  s, int   * d)
{
    queue
< int >  q;
    
bool  inq[kMaxn];
    memset(d,
0x7f ,kMaxn * sizeof ( int ));
    memset(inq,
false ,kMaxn * sizeof ( bool ));
    d[s]
= 0 ;
    q.push(s);
    inq[s]
= true ;
    
while ( ! q.empty())
    {
        
int  u(q.front());q.pop();inq[u] = false ;
        
for (list < Type > ::iterator i = g[u].begin();i != g[u].end();i ++ )
            
if (d[i -> v] > d[u] + i -> w)
            {
                d[i
-> v] = d[u] + i -> w;
                
if ( ! inq[i -> v])
                {
                    q.push(i
-> v);
                    inq[i
-> v] = true ;
                }
            }
    }
}

int  main()
{
    
while (scanf( " %d%d " , & n, & m) == 2 )
    {
        
for ( int  i = 1 ;i <= n;i ++ )
            g[i].clear();
        
for ( int  i = 1 ;i <= m;i ++ )
        {
            
int  u,v,w;
            scanf(
" %d%d%d " , & u, & v, & w);
            g[u].push_back(Type(v,w));
            g[v].push_back(Type(u,w));
        }

        spfa(
1 ,d1);
        spfa(n,dn);

        ans
= 0x7f7f7f7f ;
        
for ( int  i = 1 ;i <= n;i ++ )
            
for (list < Type > ::iterator j = g[i].begin();j != g[i].end();j ++ )
                
if (d1[i] + j -> w + dn[j -> v] > d1[n])
                    ans
= min(ans,d1[i] + j -> w + dn[j -> v]);

        printf(
" %d\n " ,ans);
    }

    
return   0 ;
}

你可能感兴趣的:(POJ 3255 Roadblocks)