UPC:2218 Thrall’s Dream(BFS)

题意:给一个有向图,问任意两点之间能否联通。

思路:由于数据量不大,可以枚举每个点直接bfs遍历整个图,但这个过程有很多重复,可以加一些优化。比如说在当前枚举点x,它可达点y。如果y点之前已经枚举过那么就不需要再遍历y了,直接将y可达的点设为x也可达就行了。

#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=2005;
typedef long long LL;
vector<short> g[maxn];
bool can[maxn][maxn];
int n,m;
bool judge()
{
    for(int i=1; i<=n; ++i)
        for(int j=i+1; j<=n; ++j)
            if(!can[i][j]&&!can[j][i])
                return false;
    return true;
}
void bfs(int x)
{
    queue<short> que;
    que.push(x);
    while(!que.empty())
    {
        short q=que.front();
        que.pop();
        if(q<x)
        {
            for(int i=1; i<=n; ++i)
                if(can[q][i])
                    can[x][i]=true;
        }
        else
        {
            for(int i=0; i<g[q].size(); ++i)
            {
                int y=g[q][i];
                if(!can[x][y])
                {
                    can[x][y]=true;
                    que.push(y);
                }
            }
        }
    }
}
int main()
{
    int T,kase=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1; i<=n; ++i)
            g[i].clear();
        memset(can,0,sizeof(can));
        for(int i=1; i<=m; ++i)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            g[x].push_back(y);
        }
        for(int i=1; i<=n; ++i)
            bfs(i);
        if(judge())
            printf("Case %d: Kalimdor is just ahead\n",++kase);
        else
            printf("Case %d: The Burning Shadow consume us all\n",++kase);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值