CF Planets(STL+ 最短路)

在CF上做了两场比赛,又在ural上尝试做了几道题,最后还是决定以后的训练还是主要集中在CF上吧,是时候把学的知识融合一下了,而且在POJ上总是会习惯的去看discuss里的讨论,不会自己认真去想,应该换个地方练练了。不过貌似有点“出师不利”啊,昨天做了一道题,WA了整整一版也没过,最后终于想不出是哪里错了,参考了一下别人的代码,结果他们都是用STL做的,思路都一样,SPFA求最短路。于是改用STL做了一下,开始初始化小了,WA了一次就过了,然后改用二维数组又写了一遍,还是过不了第66个样例,不知道怎么办了,应该是第66的样例中有时间延迟数据很多的,我开的数组不要够大,但是二维数组不能再开大,要不就超内存了,所以还是用STL做吧。

代码:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <math.h>
#include <set>
#include <vector>
#define  N 100005
//#define  INF  1<<63
using namespace std ;

//typedef long long ll ;
const int INF =(1 << 30)  ;

vector<int>p[N] ;
vector<int>val[N] ;
set<int>tp[N] ;
int dis[N] ;
int n , m ;
bool vist[N] ;

int main()
{
    int i , x , y , z;
    //cout<<INF<<endl;
    while ( scanf ( "%d%d" , &n, &m ) != EOF )
    {

        for ( i = 1 ; i <= m ; i++ )
        {
            scanf ( "%d%d%d" , &x , &y , &z ) ;
            p[x].push_back( y ) ; val[x].push_back( z ) ;
            p[y].push_back( x ) ; val[y].push_back( z ) ;
        }

        //set<int>tp[N] ;
        for ( i = 1 ; i <= n ; i++ )
        {
            tp[i].clear();
            scanf ( "%d" , &x ) ;
            while ( x-- )
            {
                scanf ( "%d" , &y ) ;
                tp[i].insert( y ) ;
            }
        }

        for ( i = 0 ; i <= n ; i++ )
        {
            dis[i] = INF ;
            vist[i] = false ;
        }
        queue<int>q ;
        dis[1] = 0 ;vist[1] = true ;
        q.push( 1 ) ;

        while ( !q.empty())
        {
            x = q.front() ;
            q.pop();
            vist[x] = false ;
            y = dis[x] ;
            while ( tp[x].count( y )) y++ ;
            for ( i = 0 ; i < p[x].size() ; i++ )
            {
                z = p[x][i] ;
                int t = val[x][i] ;
                if ( dis[z] > y + t )
                {
                    dis[z] = y + t ;
                    if ( !vist[z] )
                    {
                        vist[z] = true ;
                        q.push( z ) ;
                    }
                }
            }
        }
        for( i = 1 ; i <= n ; i++ )
        {
            p[i].clear();
            val[i].clear();
        }
        if ( dis[n] == dis[0] )
        dis[n] = -1 ;
        printf ( "%d\n" , dis[n] ) ;
    }
    return 0 ;
}
原文地址:https://www.cnblogs.com/misty1/p/2745357.html