【 题集 】 【kuangbin带你飞】专题一 简单搜索 更新 ing ......

本文总结了算法挑战赛中遇到的各类问题,包括棋盘问题、迷宫逃脱、寻找油井等经典算法题目,并提供了详细的解决方案及代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    今天开始做,感觉好吃力,好水好弱、、、

    可能接下来是继续,或者换其它的专题了吧、、、

A - 棋盘问题

Description

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

Input

输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。

Output

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1

Sample Output

2
1


    简单搜索,只需一层一层往下搜即可、、

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;

int n, m;
int ans;  // 方案数
char tt[10][10];  //
bool vis[10]; // 表示第i 列已经有棋子

void dfs(int s, int cnt)
{
    if(cnt == m)
    {
        ans ++;
        return;
    }
    for(int i = s; i <= n; i ++)
    {
        for(int j = 1; j <= n; j ++)
        {
            if(tt[i][j] == '#' && !vis[j])
            {
                vis[j] = 1;
                dfs(i + 1, cnt + 1);
                vis[j] = 0;
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        if(n == -1 && m == -1)
            break;
        memset(tt, 0, sizeof(tt));
        memset(vis, 0, sizeof(vis));
        ans = 0;
        for(int i = 1; i <= n; i ++)
        {
            scanf("%s",tt[i] + 1);
        }
        dfs(1, 0);
        printf("%d\n",ans);
    }
    return 0;
}



B - Dungeon Master
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides. 

Is an escape possible? If yes, how long will it take? 

Input

The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size). 
L is the number of levels making up the dungeon. 
R and C are the number of rows and columns making up the plan of each level. 
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.

Output

Each maze generates one line of output. If it is possible to reach the exit, print a line of the form 
Escaped in x minute(s).

where x is replaced by the shortest time it takes to escape. 
If it is not possible to escape, print the line 
Trapped!

Sample Input

3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

Sample Output

Escaped in 11 minute(s).
Trapped!

不知道哪里错了诶 - -

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;

#define N 40
#define Max 1 << 29

struct node
{
    int x, y, z;
    int dep;
};

int l, r, c;
node sa;

char tt[N][N][N];
bool vis[N][N][N];

int dir[6][3] = { {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} };

bool judge(node a)
{
    if(a.x < 0 || a.y < 0 || a.z < 0 || a.x >= l || a.y >= r || a.z >= c || vis[a.x][a.y][a.z] || tt[a.x][a.y][a.z] == '#')
        return false;
    return true;
}

void bfs()
{
    node tmp_2, tmp_3;
    queue<node> qe;
    while(!qe.empty())
    {
        qe.pop();
    }
    vis[sa.x][sa.y][sa.z] = true;
    qe.push(sa);
    while(!qe.empty())
    {
        tmp_3 = qe.front();
        qe.pop();
        for(int i = 0; i < 6; i ++)
        {
            tmp_2 = tmp_3;
            tmp_2.x += dir[i][0];
            tmp_2.y += dir[i][1];
            tmp_2.z += dir[i][2];
            tmp_2.dep = tmp_3.dep + 1;

            if(!judge(tmp_2))
                continue;

            if(tt[tmp_2.x][tmp_2.y][tmp_2.z] == 'E')
            {
                printf("Escaped in %d minute(s).\n",tmp_2.dep);
                return;
            }

            vis[tmp_2.x][tmp_2.y][tmp_2.z] = true;
            qe.push(tmp_2);
        }
    }
    printf("Trapped\n");
}

int main()
{
    while(~scanf("%d%d%d",&l,&r,&c))
    {
        if(l == 0 && r == 0 && c == 0)
            break;

        memset(vis, false, sizeof(vis));
        memset(tt, '#', sizeof(tt));

        for(int i = 0; i < l; i ++)
        {
            for(int j = 0; j < r; j ++)
            {
                scanf("%s",&tt[i][j]);
            }
        }

        for(int i = 0; i < l; i ++)
        {
            for(int j = 0; j < r; j ++)
            {
                for(int k = 0; k < c; k ++)
                {
                    if(tt[i][j][k] == 'S')
                    {
                        sa.x = i;
                        sa.y = j;
                        sa.z = k;
                        sa.dep = 0;
                    }
                }
            }
        }


        /*for(int i = 0; i < l; i ++)
        {
            for(int j = 0; j < r; j ++)
            {
                for(int k = 0; k < c; k ++)
                {
                    printf("%c",tt[i][j][k]);
                }
                printf("\n");
            }
            printf(*/
        bfs();
    }
    return 0;
}


C - Catch That Cow

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 orX + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N andK

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

    这题原本做过的,也是第一次用队列做的bfs ,代码的话,有点因为Tab 的问题 - -#

   

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

#define MAX 100005
queue<int> q;
int step[MAX];
bool vis[MAX];
int n, m;
int next,head;

int bfs()
{
	q.push(n);
	step[n] = 0;
	vis[n] = 1;
	while(! q.empty())
	{
		head = q.front();
		q.pop();
		for(int i = 0 ; i < 3; i ++)
		{
			if(i == 0)
				next = head - 1;
			else if(i == 1)
				next = head + 1;
			else
				next = head * 2;
			if(next > MAX || next < 0)
				continue;
			if(!vis[next])
			{
				q.push(next);
				step[next] = step[head] + 1;
				vis[next] = 1;
			}
			if(next == m)
				return step[next];
		}
	}
	return 0;
}

int main()
{

	while(~scanf("%d%d",&n, &m))
	{
	    memset(vis, 0, sizeof(vis));
		if(n >= m)
			printf("%d\n", n - m);
		else
			printf("%d\n", bfs());
	}
	return 0;
}



E - Find The Multiple
Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

Description

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

Input

The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

Output

For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

Sample Input

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;

#define N 120
#define Max 1 << 29

int n;
int tt;
bool flag;

void dfs(long long int x, int dep)
{
    if(flag)
        return;
    if(dep >= tt)
        return;
    if(x % n == 0)
    {
        printf("%lld\n",x);
        flag = true;
        return;
    }

    dfs(x * 10, dep + 1);
    dfs(x *10 + 1, dep + 1);
}

int main()
{
    while(~scanf("%d",&n),n)
    {
        flag = false;
        for(tt = 1; ; tt ++)
        {
            if(flag)
                break;
            dfs(1,0);
        }
    }
    return 0;
}


K - 迷宫问题


Description

定义一个二维数组:
int maze[5][5] = {

 0, 1, 0, 0, 0,

 0, 1, 0, 1, 0,

 0, 0, 0, 0, 0,

 0, 1, 1, 1, 0,

 0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)


    因为懒(不会),所以就直接printf 了  0.0

  

#include <stdio.h>

int main()
{
    printf("(0, 0)\n(1, 0)\n(2, 0)\n(2, 1)\n(2, 2)\n(2, 3)\n(2, 4)\n(3, 4)\n(4, 4)\n");
}


L - Oil Deposits


Description

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
 

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
 

Output

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
 

Sample Input

1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
 

Sample Output

0 1 2 2

    可以用深搜来做,每次遍历的时候,把@ 换为 * 就可以了,最后记录@ 的个数,该题有八个方位、、


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;

int dir[8][2] = {1, -1, 1, 0, 1 , 1, 0, 1, 0, -1, -1, 1, -1 ,0, -1, -1};
char tt[110][110];
int n, m;

void dfs(int x, int y)
{
    tt[x][y] = '*';
    for(int i = 0; i < 8; i ++)
    {
        int nn = x + dir[i][0];
        int mm = y + dir[i][1];
        if(nn < 0 || mm < 0 || nn >= n || mm >= m)
            continue;
        if(tt[nn][mm] == '@')
            dfs(nn, mm);
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m), n, m)
    {
        memset(tt, 0, sizeof(tt));
        for(int i = 0; i < n; i ++)
        {
            scanf("%s",tt[i]);
        }
        int cnt = 0;

        for(int i = 0; i < n; i ++)
        {
            for(int j = 0; j < m; j ++)
            {
                if(tt[i][j] == '@')
                {
                    dfs(i, j);
                    cnt ++;
                }
            }
        }
        printf("%d\n", cnt);
    }
}

N - Find a way
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki. 
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest. 
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes. 
 

Input

The input contains multiple test cases. 
Each test case include, first two integers n, m. (2<=n,m<=200). 
Next n lines, each line included m character. 
‘Y’ express yifenfei initial position. 
‘M’    express Merceki initial position. 
‘#’ forbid road; 
‘.’ Road. 
‘@’ KCF 
 

Output

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
 

Sample Input

4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
 

Sample Output

66 88 66
 

写完这题 感觉 对  队列的bfs 有挺大的收获了、、

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;

#define N 210
#define INF 1 << 29

struct node
{
    int x, y;
    int step;
};

int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
bool vis[N][N];
char maz[N][N];
node s1, s2;
int n, m;
int s1s[N][N];
int s2s[N][N];


bool judge(node t)
{
    if(t.x < 0 || t.y < 0 || t.x >= n || t.y >= m || maz[t.x][t.y] == '#' || vis[t.x][t.y])
        return false;
    return true;
}

void bfs(node a, int ans[][N])
{
    //printf("st %d %d\n", a.x, a.y);
    memset(vis, false, sizeof(vis));
    memset(ans, 0, sizeof(ans));
    node tmp, te;
    queue<node> q;
    int cnt = 1;
    while(!q.empty())
    {
        q.pop();
    }

    vis[a.x ][a.y] = true;
    q.push(a);

    while(!q.empty())
    {
        tmp = q.front();
        //printf("tttt %d %d %d \n", tmp.x, tmp.y, tmp.step);
        q.pop();
        for(int i = 0; i < 4; i ++)
        {
            te = tmp;
            te.x += dir[i][0];
            te.y += dir[i][1];
            te.step = tmp.step + 1;
           // printf("te %d %d \n", te.x, te.y);
            if(!judge(te))
            {
                continue;
            }
            if(maz[te.x][te.y] == '@')
            {
                ans[te.x][te.y] = te.step;
                //printf("step %d\n", te.step);
            }
            vis[te.x][te.y] = true;
            q.push(te);
            //printf("cnt %d\n", cnt ++ );
        }
    }
    return;
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        for(int i = 0; i < n; i ++)
        {
            scanf("%s",&maz[i]);
        }

        int amt = 0;
        for(int i = 0; i < n; i ++)
        {
            for(int j = 0; j < m; j ++)
            {
                if(maz[i][j] == 'Y')
                {
                    s1.x = i;
                    s1.y = j;
                    s1.step = 0;
                }
                else if(maz[i][j] == 'M')
                {
                    s2.x = i;
                    s2.y = j;
                    s2.step = 0;
                }
            }
        }
        int an = INF;
        bfs(s1,s1s);
        bfs(s2,s2s);
        for(int i = 0; i < n ; i ++)
        {
            for(int j = 0; j < m; j ++)
            {
                if(maz[i][j] == '@')
                {
                    if(s1s[i][j] != 0 && s2s[i][j] != 0)
                    {
                        an = min(an, s1s[i][j] + s2s[i][j]);
                    }
                }
            }
        }
        printf("%d\n",an *11);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值