bfs以及hash入门题各一道

七月初打的某场训练赛的题,当时还真是啥也不会,今天再次挑战,感觉还不错。

杰哥的疑问

https://ac.nowcoder.com/acm/contest/37219/G

 这题官方题解说是二分,但是我觉得是很明显的hash啊。由于i一定要小于j,所以可以维护一个map嘛。

// Problem: 杰哥的疑问
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/37219/G
// Memory Limit: 524288 MB
// Time Limit: 4000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

using namespace std;
int main()
{
    int n, m;
    cin >> n >> m;
    map<int,int> mp;
    long long count=0;
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        count+=mp[m-x];
        mp[x]++;
    }
    printf("%lld",count);
    return 0;
}

珈乐的迷宫

https://ac.nowcoder.com/acm/contest/37219/E 

这题就是多个入口一个出口,但实际上你可以从出口开始bfs,只做一趟bfs就可以解决了。

// Problem: 佳乐的迷宫
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/37219/E
// Memory Limit: 524288 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

using namespace std;
const int N = 1005;
int n, m, k;
char a[N][N];
int num[N][N];
int vis[N][N];
struct node
{
    int x, y;
};
bool ok(int x, int y)
{
    if (x < 1 || x > n || y < 1 || y > m)
        return false;
    return true;
}
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int b[1000005];
void bfs(int sx, int sy)
{
    int step = 0;
    struct node cur, nex;
    cur.x = sx, cur.y = sy;
    vis[cur.x][cur.y] = 1;
    queue<node> qu;
    qu.push(cur);
    while (!qu.empty())
    {
        cur = qu.front();
        qu.pop();

        for (int i = 0; i < 4; i++)
        {
            nex.x = cur.x + dir[i][0];
            nex.y = cur.y + dir[i][1];
            if (ok(nex.x, nex.y) && !vis[nex.x][nex.y] && a[nex.x][nex.y] != '#')
            {
                if (a[nex.x][nex.y] == 'e')
                {
                    step++;
                    b[step] = num[nex.x][nex.y];
                }
                vis[nex.x][nex.y] = 1;
                qu.push(nex);
            }
        }
    }
    printf("%d\n", step);
    sort(b + 1, b + 1 + step);
    for (int i = 1; i <= step; i++)
    {
        printf("%d ", b[i]);
    }
}
int main()
{
    cin >> n >> m >> k;
    memset(vis, 0, sizeof(vis));
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> a[i][j];
        }
    }
    vector<node> v;
    for (int i = 1; i <= k; i++)
    {
        int x, y;
        cin >> x >> y;
        a[x][y] = 'e';
        num[x][y] = i;
    }
    int sx, sy;
    cin >> sx >> sy;
    bfs(sx, sy);
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值