点我看题目

题意 : 一个司机要从1点到达n点,1点到n点中有一些点有宾馆,司机的最长开车时间不能超过10小时,所以要在10小时之内找到宾馆休息,但是为了尽快的走到n点,问最少可以经过几个宾馆。

思路 : 这个题太狠了,简直不是人做的。。。。可以BFS一下,然后在B之前先D一下能走的路。当然也可以用SPFA+Floyd。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <vector>

using namespace std ;

struct node
{
    int u,w ;
}temp ;
struct BFS
{
    int u,w,step ;
}t,t1 ;
const int maxn = 10110 ;
const int INF = 999999999 ;
vector<node> vec[maxn] ;
queue<BFS>Q ;
bool hashh[10110],vis[maxn] ;
int n,m,h ;
int ret[maxn],st[maxn] ;

void DFS(int u,int w,int step)
{
    if(vis[u]) return  ;
    if(w >= ret[u]) return ;
    if(w > 0) ret[u] = w ;
    if(hashh[u] && w == 0) vis[u] = true ;
    for(int i = 0 ; i < vec[u].size() ; i++)
    {
        if(hashh[vec[u][i].u] && (!vis[vec[u][i].u]) && (w+vec[u][i].w<=600) && (step + 1 < st[vec[u][i].u]))
        {
            t.u = vec[u][i].u ;
            //t.w = vec[u][i].w ;
            t.step = step+1 ;
            st[t.u] = t.step ;
            Q.push(t) ;
        }
        if(w+vec[u][i].w <= 600)
            DFS(vec[u][i].u,w+vec[u][i].w,step) ;
    }
}
void BFS()
{
    while(!Q.empty())
        Q.pop() ;
    t.u = 1 ;
    t.w = t.step = 0 ;
    Q.push(t) ;
    while(!Q.empty())
    {
        t1 = Q.front() ;
        Q.pop() ;
        if(t1.u == n)
        {
            printf("%d\n",t1.step-1) ;
            return ;
        }
        DFS(t1.u,0,t1.step) ;
    }
    printf("-1\n") ;
    return ;
}
int main()
{
    while(~scanf("%d",&n))
    {
        if(n == 0) break ;
        for(int i = 0 ; i <= n ; i++)
        {
            vector<node>().swap(vec[i]) ;
            ret[i] = st[i] = INF ;
            hashh[i] = vis[i] = false ;
        }
        hashh[1] = hashh[n] = true ;
        scanf("%d",&m) ;
        int s ;
        for(int i = 0 ; i < m ; i++)
        {
            scanf("%d",&s) ;
            hashh[s] = true ;
        }
        scanf("%d",&h) ;
        int u,v,w ;
        for(int i = 0 ; i < h ; i++)
        {
            scanf("%d %d %d",&u,&v,&w) ;
            temp.u = v ;
            temp.w = w ;
            vec[u].push_back(temp) ;
            temp.u = u ;
            vec[v].push_back(temp) ;
        }
        BFS() ;
    }
    return 0 ;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-10-03
  • 2021-10-12
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-16
猜你喜欢
  • 2021-08-21
  • 2021-10-13
  • 2021-12-05
  • 2022-01-06
  • 2021-06-13
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案