zoukankan      html  css  js  c++  java
  • [BFS][51nod]1649 齐头并进

    A了 可是为什么呢??

    矩阵存边

    bfs搜索

    //#pragma GCC optimize(2)
    #include <cstdio>
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
    #include <cctype>
    #include <string>
    #include <cstring>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <set>
    #include <map>
    #include <ctime>
    #include <vector>
    #include <fstream>
    #include <list>
    #include <iomanip>
    #include <numeric>
    using namespace std;
    
    typedef long long ll;
    
    const int MAXN = 4e2 + 10;
    
    int edge[MAXN][MAXN] ={0};
    bool trainu[MAXN] = {0};
    bool busu[MAXN] = {0};
    
    int n, m;
    
    struct bfsnode
    {
        int now, step;
        bfsnode(int a, int b)
        {
            now = a, step = b;
        }
    };
     
    int bfstrain()
    {
        int anstrain = 0;
    
        queue <bfsnode> Q;
    
        Q.push(bfsnode(1, 0));
    
        while(!Q.empty())
        {
            bfsnode t = Q.front();
    
            Q.pop();
    
            if(!trainu[t.now])
            {
                if(t.now == n)
                {
                    return t.step;
                }
    
                trainu[t.now] = true;
    
                for(int j = 1; j <= n; j++)
                {
                    if(edge[t.now][j])
                    {
                        Q.push(bfsnode(j, t.step + 1));
                    }
    
                }
            }
        }
        return -1;
    }
    
    int bfsbus()
    {
        int ansbus = 0;
    
        queue <bfsnode> Q;
    
        Q.push(bfsnode(1, 0));
    
        while(!Q.empty())
        {
            bfsnode t = Q.front();
    
            Q.pop();
    
            if(!busu[t.now])
            {
                if(t.now == n)
                {
                    return t.step;
                }
    
                busu[t.now] = true;
    
                for(int j = 1; j <= n; j++)
                {
                    if(!edge[t.now][j])
                    {
                        Q.push(bfsnode(j, t.step + 1));
                    }
    
                }
            }
        }
        return -1;
    }
    
    int main()
    {
        cin>>n>>m;
    
        int x, y;
        
        for(int i = 0; i < m; i++)
        {
            cin>>x>>y;
            edge[x][y] = 1;
            edge[y][x] = 1;
        }
        
        int tlen = bfstrain(), blen = bfsbus();
    
        if(tlen == -1 || blen == -1)
            cout<<"-1"<<endl;
        else
            cout<<max(tlen, blen)<<endl;
    
        return 0;
    }
  • 相关阅读:
    SpringMvc---Ant通配符
    mybatis 数据库语句
    shiro 静态页面资源不显示 解决方案
    http错误汇总
    关于代码质量与逻辑
    shiro 过滤属性的意义
    java思维导图
    E
    LCIS HDU
    E
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270446.html
Copyright © 2011-2022 走看看