搜索算法BFS和DFS

A - 棋盘问题

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放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 <iostream>
#include <cstring>
#include <algorithm>
#include <string.h>
const int max_n = 10;
using namespace std;
bool vis[max_n];
char mp[max_n][max_n];
int n, k, sum;
int dfs(int x, int num)
{
    if (num >= k) 
    { 
        sum++;
        return 0; 
    }
    for (int i = x; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (!vis[j] && mp[i][j] == '#') //棋子只能在棋盘区域
            {
                vis[j] = true;//设置为本行有棋子了
                dfs(i + 1, num + 1);//进行下一行的计算
                vis[j] = false;//递归结束后,设置本行没有棋子了
            }
        }
    }
}
int main()
{
    while (1)
    {
        cin >> n >> k;
        if (n == -1 && k == -1)break;
        memset(vis, false, sizeof(vis));
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
                cin >> mp[i][j];
        }
        sum = 0;
        dfs(1, 0);
        cout << sum << endl;
    }
    return 0;
}

B - Perket

你有 NN 种配料,每种配料有酸度 SS 和苦度 BB 。用这些配料做成Perket时,总的酸度为所有配料酸度的乘积,总的苦度是所有配料苦度的和。你至少需要添加一种配料。

为了使口感适中,总的酸度和苦度之差的绝对值应该尽可能小,求这个最小值。

输入
第一行 11 个整数 N \ (1\le N\le 10)N (1≤N≤10) —— 配料的数量。

接下来 NN 行每行 22 个整数 S_iS
i

和 B_iB
i

—— 每种配料的酸度和苦度。如果用所有配料来做Perket,总的酸度和苦度都 \le 10^9≤10
9

输出
NN 行,每行 11 个整数 —— 所求的最小值。

Sample Input 1 Sample Output 1
1
3 10
7
Sample Input 2 Sample Output 2
2
3 8
5 8
1
Sample Input 3 Sample Output 3
4
1 7
2 6
3 8
4 9
1
代码:

#include<iostream>
#include<vector>
#include<climits>
using namespace std;
typedef long long ll;
const int N=10;
int ans = INT_MAX;
vector<int>s(N + 1);
vector<int>b(N + 1);
int vis[N];
void fun(int i,int end)
{
	if (i == end)
	{
		ll s_sum = 1;
		ll b_sum = 0;
		bool flag = false;
		for (int j = 0; j < i; j++)
		{
			if (vis[j])
			{
				flag = true;
				s_sum *= s[j];
				b_sum += b[j];
			}
		}
		if (flag==true&&abs(s_sum - b_sum) < ans)
			ans = abs(s_sum - b_sum);
		return;
	}
	vis[i] = 1;
	fun(i + 1, end);
	vis[i] = 0;
	fun(i + 1, end);
}
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> s[i] >> b[i];
	}
	fun(0,n);
	cout << ans << endl;
	return 0;
}

C - 全排列

给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有 ‘a’ < ‘b’ < … < ‘y’ < ‘z’,而且给定的字符串中的字母已经按照从小到大的顺序排列。

输入格式
输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在 11 到 66 之间。

输出格式
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义:

已知 S = s_1s_2…s_k, T = t_1t_2…t_kS=s
1

s
2

…s
k

,T=t
1

t
2

…t
k

,则 S < TS<T 等价于,存在 p (1 \le p \le k)p(1≤p≤k),使得 s_1 = t_1, s_2 = t_2, …, s_{p - 1} = t_{p - 1}, s_p < t_ps
1

=t
1

,s
2

=t
2

,…,s
p−1

=t
p−1

,s
p

<t
p

成立。

Sample Input
abc
Sample Output
abc
acb
bac
bca
cab
cba
代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void swap(string &str,int i,int j)
{
	char tmp = str[i];
	str[i] = str[j];
	str[j] = tmp;
}

void getPermutation(vector<string>&res, string str, int begin)
{
	if (begin == str.size())
	{
		res.push_back(str);
	}
	else
	{
		for (int i = begin; i < str.size(); i++)
		{
			if (str[i] == str[begin] && i != begin)
				continue;
			swap(str,i,begin);
			getPermutation(res, str, begin + 1);
			swap(str,i,begin);
		}
	}
}
vector<string> Permutation(string& str)
{
	vector<string>res;
	if (str.size() == 0)
	{
		return res;
	}
	getPermutation(res, str, 0);
	sort(res.begin(), res.end());
	return res;
}
int main()
{
	string str;
	cin >> str;
	vector<string>res = Permutation(str);
	for (auto it = res.begin(); it != res.end(); it++)
	{
		cout << *it << endl;
	}
	return 0;
}

D - 自然数拆分

对于任意大于 11 的自然数 nn,总是可以拆分成若干个小于 nn 的自然数之和。

现请你编写程序求出 nn 的所有拆分。

输入格式
输入文件共一行,包含一个自然数,即要拆分的自然数 n(1 \le n \le 20)n(1≤n≤20)。

输出格式
输出文件有若干行,每行包含一个等式,即代表一种可行的拆分(格式与顺序参见样例)。

Sample Input
5
Sample Output
5=1+1+1+1+1
5=1+1+1+2
5=1+1+3
5=1+2+2
5=1+4
5=2+3
代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int x[20]={0};
int N;
void back(int n, int m)
{
	int res;
	for (int i = 1; i <= n; i++)
	{
		if (i >= x[m - 1])
		{
			x[m] = i;
			res = n - i;
			if (res == 0 && m > 1)
			{
				cout << N << "=";
				for (int j = 1; j < m; j++)
				{
					cout << x[j] << "+";
				}
				cout <<x[m]<< endl;
			}
			else
			{
				back(res, m + 1);
			}
			x[m] = 0;
		}
		
	}
}
int main()
{
	cin >> N;
	back(N, 1);
	return 0;
}

E - Prime Ring Problem

题意翻译
输入正整数 n,把整数 1,2,…,n 排成一个环,使得相邻两个整数之和均为素数。输出时,从整数 1 开始逆时针排列。同一个环恰好输出一次。n≤16,保证一定有解。

多组数据,读入到EOF结束。

第 i 组数据输出前加上一行Case i:

相邻两组输出中间加上一个空行。

输入样例
6
8

输出样例
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

输出格式提示
行末无空格
最后一个Case输出后不换行
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<cmath>
#include<queue>
#include<climits>
using namespace std;
int n;
vector<int>vis(20);
vector<int>ans(20);
bool isPrime(int x)
{
    int t = (int)sqrt(x);
    for (int i=2; i <= t; i++)
    {
        if (x % i == 0)
            return false;
    }
    return true;
}
void dfs(int k)
{
    if (k>n)
    {
        if (isPrime(ans[1] + ans[k-1]))
        {
            for (int i = 1; i < n; i++)
            {
                cout<<ans[i]<<" ";
            }
            cout<<ans[n]<<endl;
        }
        return;
    }
    for (int i = 2; i <= n; i++)
    {
        if (!vis[i])
        {
            if (isPrime(ans[k-1] + i))
            {
                vis[i] = true;
                ans[k] = i;
                dfs(k + 1);
                vis[i] = false;
            }
        }
    }
}
int main()
{
    int Case=0;
    while (cin >> n)
    {
        if (Case)
            cout << endl;
        Case++;
        for (int i = 0; i <= n; i++)
        {
            vis[i] = false;
            ans[i] = 0;
        }
        ans[1] = 1;
        vis[1] = true;
        cout << "Case " << Case << ":" << endl;
        dfs(2);
    }
    return 0;
}

F - Red and Black

有一个长方形的房间,覆盖了正方形的磁砖。每块磁砖的颜色,要么是红色,要么是黑色。一名男子站在一块黑色的磁砖上。他可以从一块磁砖移至相邻四块磁砖中的某一块。但是,他不允许在红色磁砖上移动,他只允许在黑色磁砖上移动。

编写一个程序,使得他允许重复上述的移动,判断他所能到达的黑色磁砖的数量。
输入
输入由多个数据集组成。数据集的起始行包含了两个正整数 W 和 H;W 和 H 分别是 x- 和 y- 方向的磁砖数量。W 和 H 不超过 20 。

在数据集中,还有 H 行,每行包含了 W 个字符。每个字符按如下方式表示一块磁砖的颜色。

‘.’ - 一块黑色的磁砖
‘#’ - 一块红色的磁砖
‘@’ - 一名男子,站在一块黑色磁砖上 (在一个数据集中,恰好出现一次)

以包含两个 0 的一行,表示输入结束。
输出
对于每个数据集,程序应当输出一行,包含他从初始磁砖所能抵达的磁砖数量 (包括初始磁砖自身)。
示例输入
6 9
…#.
…#





#@…#
.#…#.
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.

11 6
…#…#…#…
…#…#…#…
…#…#…###
…#…#…#@.
…#…#…#…
…#…#…#…
7 7
…#.#…
…#.#…
###.###
…@…
###.###
…#.#…
…#.#…
0 0
示例输出
45
59
6
13
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<queue>
using namespace std;
char mp[25][25];
bool vis[25][25];
int n, m;
int cnt = 0;
int dir_x[4] = { -1,1,0,0};
int dir_y[4] = { 0,0,-1,1};
void bfs(int x,int y)
{
    queue<int>p;
    queue<int>q;
    p.push(x);
    q.push(y);
    vis[x][y] = true;
    cnt++;
    while (!p.empty() && !q.empty())
    {
        int xx = p.front();
        int yy = q.front();
        p.pop();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int dx = xx + dir_x[i];
            int dy = yy + dir_y[i];
            if (dx >= 1 && dx <= m && dy >= 1 && dy <= n)
            {
                if (!vis[dx][dy] && mp[dx][dy] == '.')
                {
                    vis[dx][dy] = true;
                    cnt++;
                    p.push(dx);
                    q.push(dy);
                }
            }
        }
    }
}

int main()
{
    while (1)
    {
        cin >> n >> m;
        if (m == 0 && n == 0)
            break;
        int start_x = 0, start_y = 0;
        for (int i = 1; i <= m; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                cin >> mp[i][j];
                if (mp[i][j] == '@')
                {
                    start_x = i;
                    start_y = j;
                }
            }

        }
        cnt = 0;
        for (int i = 1; i <= m; i++)
        {
            for (int j = 1; j <= n; j++)
                vis[i][j] = false;
        }
        bfs(start_x, start_y);
        cout << cnt << endl;
    }
    
    return 0;
}

G - Knight Moves

题目描述
原题来自:POJ 1915

编写一个程序,计算一个骑士从棋盘上的一个格子到另一个格子所需的最小步数。骑士一步可以移动到的位置由下图给出。

Picture 1

输入格式
第一行给出骑士的数量 nn。
在接下来的 3n3n 行中,每 33 行描述了一个骑士。其中,

第一行一个整数 LL 表示棋盘的大小,整个棋盘大小为 L\times LL×L;
第二行和第三行分别包含一对整数 (x,y)(x,y),表示骑士的起始点和终点。假设对于每一个骑士,起始点和终点均合理。
输出格式
对每一个骑士,输出一行一个整数表示需要移动的最小步数。如果起始点和终点相同,则输出 00。

样例
Input Output
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
5
28
0
数据范围与提示
对于 100%100% 的数据,有 4\le L\le 3004≤L≤300,保证 0\le x,y\le L-10≤x,y≤L−1。
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<queue>
using namespace std;
bool vis[310][310];
int n;
int start_x, start_y, end_x, end_y;
int cnt;
int dir_x[8] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int dir_y[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
struct node
{
    int x;
    int y;
    int step;
};
void bfs()
{
    if (start_x == end_x && start_y == end_y)
    {
        
        return;
    }   
    queue<node>p;
    node _node;
    _node.x = start_x;
    _node.y = start_y;
    _node.step = 0;
    vis[start_x][start_y] = true;
    p.push(_node);
    while (!p.empty())
    {
        node head = p.front();
        p.pop();
        if (head.x == end_x && head.y == end_y)
        {
            cnt = head.step;
            break;
        }
        for (int i = 0; i < 8; i++)
        {
            int dx = head.x + dir_x[i];
            int dy = head.y + dir_y[i];
            if (dx >= 0 && dx < n && dy >= 0 && dy < n)
            {
                if (!vis[dx][dy])
                {
                    vis[dx][dy] = true;
                    node newNode;
                    newNode.x = dx;
                    newNode.y = dy;
                    newNode.step = head.step + 1;
                    p.push(newNode);
                }
            }
        }
    }
}

int main()
{
    int k;
    cin >> k;
    while (k>0)
    {
        cin >> n;
        cin >> start_x >> start_y;
        cin>>end_x >> end_y;
        cnt = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
                vis[i][j] = false;
        }
        bfs();
        cout << cnt<<endl;
        k--;
    }
    
    return 0;
}

H - Oil Deposits

某公司负责探测地下油层,每次处理一个大的矩形区域。先创建一个网格,将土地划分为许多方形块,然后用传感设备分别探测每个地块,以确定该地块是否含有石油。一块含有石油的土地叫做pocket。如果两个pocket边相邻或对角相邻,则它们属于同一油层的一部分。你的工作是确定在一个网格有多少不同的油层。

Input
输入包含多组数据。每组数据都以包含m和n的一行开始,m和n是网格中行和列的数量(1 <= m <= 100,1 <= n <= 100),由一个空格分隔。如果m = 0,则表示输入结束。下面是m行,每行有n个字符(不包括行尾字符)。每个字符对应一块土地,要么是“*”,代表没有油,要么是“@”,代表一个pocket。

Output
输出网格有多少不同的油层。

Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0
Sample Output
0
1
2
2
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<queue>
using namespace std;
char mp[105][105];
bool vis[105][105];
int n, m;
int cnt = 0;
int dir_x[8] = { 0,-1,-1,-1,0,1,1,1 };
int dir_y[8] = { -1,-1,0,1,1,1,0,-1 };
void bfs(int x, int y)
{
    queue<int>p;
    queue<int>q;
    p.push(x);
    q.push(y);
    while (!p.empty() && !q.empty())
    {
        int dx = p.front();
        int dy = q.front();
        p.pop();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int xx = dx + dir_x[i];
            int yy = dy + dir_y[i];
            if (xx >= 1 && xx <= n && yy >= 1 && yy <= m)
            {
                if (mp[xx][yy] == '@' && !vis[xx][yy])
                {
                    vis[xx][yy] = true;
                    p.push(xx);
                    q.push(yy);
                }
            }
        }
    }
    if (p.empty() && q.empty())
    {
        cnt++;
    }
}

int main()
{
    while (1)
    {
        cin >> n >> m;
        if (n == 0 && m == 0)
            break;
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
                cin >> mp[i][j];
        }
        cnt = 0;
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                vis[i][j] = false;
            }
        }
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                if (mp[i][j] == '@' && !vis[i][j])
                    bfs(i, j);
            }
        }
        cout << cnt << endl;
    }
   
    return 0;
}

I - Lake Counting

由于最近的降雨,农夫约翰的农田里形成了不同位置的水塘。农田被表示为一个矩形,它包含了 N x M (1 <= N <= 100; 1 <= M <= 100) 个小方格。每个方格中,要么包含了水 (‘W’),要么包含了旱地 (’.’)。农夫约翰想要弄清楚,他的农田中形成了多少个水塘。一个水塘是由包含了水的方格连通而成,这里一个方格被视作与周围的全部八个方格相邻。

给出农夫约翰的农田数据图,判断图中有多少个水塘。
输入

  • 第一行:两个以空格分隔的整数: N 和 M

  • 第 2…N+1 行:每行 M 个字符,表示农夫约翰的农田中的一行。每个字符要么是 ‘W’ 要么是 ‘.’。字符之间没有空格。
    输出

  • 第一行:农夫约翰的农田中,水塘的数量。
    示例输入
    10 12
    W…WW.
    .WWW…WWW
    …WW…WW.
    …WW.
    …W…
    …W…W…
    .W.W…WW.
    W.W.W…W.
    .W.W…W.
    …W…W.
    示例输出
    3
    提示
    输出细节:

有 3 个水塘:一个位于左上方,一个位于左下方,还有一个位于右边。
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<queue>
using namespace std;
char mp[105][105];
bool vis[105][105];
int n, m;
int cnt = 0;
int dir_x[8] = { 0,-1,-1,-1,0,1,1,1 };
int dir_y[8] = { -1,-1,0,1,1,1,0,-1 };
void bfs(int x,int y)
{
    queue<int>p;
    queue<int>q;
    p.push(x);
    q.push(y);
    while (!p.empty() && !q.empty())
    {
        int dx = p.front();
        int dy = q.front();
        p.pop();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int xx = dx + dir_x[i];
            int yy = dy + dir_y[i];
            if (xx >= 1 && xx <= n && yy >= 1 && yy <= m)
            {
                if (mp[xx][yy] == 'W'&&!vis[xx][yy])
                {
                    vis[xx][yy] = true;
                    p.push(xx);
                    q.push(yy);
                }
            }
        }
    }
    if (p.empty() && q.empty())
    {
        cnt++;
    }
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            cin >> mp[i][j];
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            if (mp[i][j] == 'W' && !vis[i][j])
                bfs(i, j);
        }
    }
    cout << cnt << endl;
    return 0;
}

J - 二叉树先序遍历

输入一个整数n(n <= 100000),表示二叉树中节点个数,编号为1~n。约定1号节点为二叉树的根节点。然后输入n行,每行包括两个整数,第i行表示编号为i的节点的左子节点和右子节点的编号。如果某个节点没有左子节点,那么对应输行的第一个整数为0;如果某个节点没有右子节点,那么对应行的第二个整数为0。
先序遍历输出此二叉树每个节点的编号,每行输出一个编号。

先序遍历(DLR),是二叉树遍历的一种,也叫做先根遍历、前序遍历、前序周游,可记做根左右。前序遍历首先访问根节点然后遍历左子树,最后遍历右子树。

Input
第一行:一个整数n 接下来n行,每行有两个整数
Output
输出n行,每行一个整数,表示节点编号。
Sample Input
5
2 5
3 4
0 0
0 0
0 0
Sample Output
1
2
3
4
5
代码:

#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
int l_child[100010];
int r_child[100010];
vector<int>ans;
void fun(int x)
{
    ans.push_back(x);
    if(l_child[x]!=0)
        fun(l_child[x]);
    if(r_child[x]!=0)
        fun(r_child[x]);
}
int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> l_child[i] >> r_child[i];
    }
    fun(1);
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << endl;
    }
    return 0;
}

K - 迷宫(一)

一天蒜头君掉进了一个迷宫里面,蒜头君想逃出去,可怜的蒜头君连迷宫是否有能逃出去的路都不知道。

看在蒜头君这么可怜的份上,就请聪明的你告诉蒜头君是否有可以逃出去的路。

输入格式
第一行输入两个整数 nn 和 mm,表示这是一个 n \times mn×m 的迷宫。

接下来的输入一个 nn 行 mm 列的迷宫。其中 ‘S’ 表示蒜头君的位置,’*‘表示墙,蒜头君无法通过,’.‘表示路,蒜头君可以通过’.'移动,'T’表示迷宫的出口(蒜头君每次只能移动到四个与他相邻的位置——上,下,左,右)。

输出格式
输出一个字符串,如果蒜头君可以逃出迷宫输出"yes",否则输出"no"。

数据范围
1 \le n, m \le 101≤n,m≤10。

Sample Input
3 4
S**.
…*.
*T
Sample Output
no
Sample Input 2
3 4
S
.

***T
Sample Output 2
yes
代码:

#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
int n, m;
int dir_x[4] = { 0,-1,1,0 };
int dir_y[4] = { 1,0,0,-1 };
void bfs(vector<vector<char>>&miss,int start_i,int start_j)
{
	queue<int>p;
	queue<int>q;
	p.push(start_i);
	q.push(start_j);
	bool flag = false;
	while (!p.empty()&&!q.empty())
	{
		int x = p.front();
		int y = q.front();
		p.pop(); q.pop();
		//cout << x << " " << y << endl;
		if (miss[x][y] == 'T')
		{
			flag = true;
			break;
		}
		miss[x][y] = '*';
		for (int i = 0; i < 4; i++)
		{
			int dx = dir_x[i]+x;
			int dy = dir_y[i]+y;
			if (miss[dx][dy] == '*' || dx < 1 || dx > n || dy < 1 || dy > m)
				continue;
			p.push(dx);
			q.push(dy);
		}
	}
	if (flag)
	{
		cout << "yes" << endl;
	}
	else
		cout << "no" << endl;
}
int main()
{
	cin >> n >> m;
	vector<vector<char>>miss(n + 2, vector<char>(m + 2));
	int start_i, start_j;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			cin >> miss[i][j];
			if (miss[i][j] == 'S')
			{
				start_i = i;
				start_j = j;
			}
		}
	}
	bfs(miss, start_i, start_j);
	return 0;
}

L - 马走日

马在中国象棋以日字形规则移动。请编写一段程序,给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。

Input
第一行为整数T(T < 10),表示测试数据组数。每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。(0<=x<=n-1,0<=y<=m-1, m < 6, n < 6)
Output
每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。
Sample Input
1
5 4 0 0
Sample Output
32
代码:

#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
int n, m;
int cnt = 0;
int dir_x[8] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int dir_y[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
bool check(vector<vector<int>>& board)
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (board[i][j] == 0)
				return false;
		}
	}
	return true;
}
void dfs(vector<vector<int>>& board, int x, int y)
{
	if (check(board))
	{
		cnt++;
		return;
	}
	for (int i = 0; i < 8; i++)
	{
		int dx = x + dir_x[i];
		int dy = y + dir_y[i];
		if (dx >= 0 && dx < n && dy >= 0 && dy < m)
		{
			if (board[dx][dy] == 0)
			{
				board[dx][dy] = 1;
				dfs(board, dx, dy);
				board[dx][dy] = 0;
			}
		}
	}
	
}
int main()
{
	int T;
	cin >> T;
	while (T > 0)
	{
		int x, y;
		cin >>n >> m >> x >> y;
		vector<vector<int>>board(n + 1, vector<int>(m + 1));
		board[x][y] = 1;
		dfs(board, x, y);
		cout << cnt << endl;
		cnt = 0;
		T--;
	}
	
	return 0;
}

M - 八皇后问题

努比亚和苏丹没有子女,所以他要从一些有集成资格的继承者中挑选一个出来继承王位。他希望这个继承者足够聪明,所以他准备了一个西洋棋盘,上面的每个格子中均有一个 1-991−99 的数字。他又准备了 88 个皇后棋子。

88 皇后的规则就是不能有任何棋子同行或者同列或者同斜线,在满足这个规则的同时,王位继承者还需要让 88 个皇后所在的位置的数字的和是最大的。

输入格式
输入一个数字 k(k\leq 20)k(k≤20),代表棋盘的数量。

接下来有 kk 个棋盘,每个棋盘有 6464 个数字,分成 88 行 88 列出入,具体可见样例,每一个数字均小于 100100。

输出格式
每一个棋盘对应输出最大的数值, 一共输出 kk 行。

Sample Input
1
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
48 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
Sample Output
260
代码:

#include<iostream>
#include<cmath>
using namespace std;
int x[21];
int n = 8;
int ans = 0;
int board[10][10];
void Print()
{
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			if (x[i] == j)
			{
				cout << "Q ";
			}
			else
			{
				cout << "X ";
			}
		}
		cout << endl;
	}
	cout << "- - - - - - - -" << endl;
}
void fun(int r) // 表示递归到第r行
{
	if (r == n + 1) // 递归到n+1行,打印跳出
	{
		
		int sum = 0;
		for (int i = 1; i <= 8; i++)
		{
			sum += board[i][x[i]];
		}
		if (ans < sum)
		{
			ans = sum;
			//Print();
		}
		return;
	}
	for (int i = 1; i <= n; ++i) // 遍历第r行中皇后的位置 x[r]=i
	{
		bool flag = true;
		x[r] = i;
		for (int j = 1; j < r; ++j) // 遍历之前行
		{
			if (x[j] == x[r] || abs(j - r) == abs(x[j] - x[r])) // 如果出现同列、同对角线,则皇后的位置要重新安排
			{
				flag = false;
				break;
			}
		}
		if (flag) // 如果皇后位置错误,不递归下一次
		{
			fun(r + 1); // 如果位置可以,找下一行
		}
	}
}
int main()
{
	int k;
	cin >> k;
	while (k > 0)
	{
		for (int i = 1; i <= 8; i++)
		{
			for (int j = 1; j <= 8; j++)
			{
				cin >> board[i][j];
			}
		}
		fun(1);
		cout << ans<<endl;
		ans = 0;
		for (int i = 1; i <= 8; i++)
			x[i] = 0;
		k--;
	}
	return 0;
}

N - 选数

已知 nn 个整数 x_1,x_2,\cdots,x_nx
1

,x
2

,⋯,x
n

,以及一个整数 kk(k<nk<n)。从 nn 个整数中任选 kk 个整数相加,可分别得到一系列的和。例如当 n=4n=4,k=3k=3,44 个整数分别为 33,77,1212,1919 时,可得全部的组合与它们的和为:

3+7+12=223+7+12=22

3+7+19=293+7+19=29

7+12+19=387+12+19=38

3+12+19=343+12+19=34

现在,要求你计算出和为素数共有多少种。

例如上例,只有一种的和为素数:3+7+19=293+7+19=29。

输入格式
输入格式为:nn,kk(1 \le n \le 20,k<n1≤n≤20,k<n)。

x_1,x_2,\cdots,x_nx
1

,x
2

,⋯,x
n

(1 \le x_i \le 50000001≤x
i

≤5000000)。

输出格式
输出格式为:一个整数(满足条件的种数)。

Sample Input
4 3
3 7 12 19
Sample Output
1
代码:

#include <iostream>
#include <algorithm>
#include<vector>
#include<cmath>
#include<queue>
using namespace std;
int nums[25];
bool vis[25];
int n, k;
int cnt = 0;
bool check(vector<int>& ans)
{
    long long sum = 0;
    for (int i = 0; i < ans.size(); i++)
    {
        sum += ans[i];
    }
    long long x = (long long)sqrt(sum);
    for (int i = 2; i <= x; i++)
    {
        if (sum % i == 0)
            return false;
    }
    return true;
}
void dfs(int r,int x)
{
    if (x >= k)
    {
        vector<int>ans;
        for (int i = 1; i <= n; i++)
        {
            if (vis[i])
                ans.push_back(nums[i]);
        }
        if (check(ans))
        {
           /* for (int i = 0; i < ans.size(); i++)
                cout << ans[i] << " ";
            cout << endl;*/
            cnt++;
        }
        return;
    }
    for (int i = r; i <= n; i++)
    {
        if (!vis[i])
        {
            vis[i] = true;
            dfs(i + 1, x + 1);
            vis[i] = false;
        }
    }
}
int main()
{
    cin >> n >> k;
    for (int i = 1; i <= n; i++)
        cin >> nums[i];
    dfs(1, 0);
    cout << cnt << endl;
    return 0;
}

单源最短路径问题

无向图
代码:
Dijkstra算法图文详解

#include <iostream>
#include <algorithm>
#include<vector>
#include<cmath>
#include<queue>
#include<climits>
using namespace std;
#define inf 0x3f3f3f3f
int paths[10][10];
bool vis[10];
int dist[10];
int n, m;//n个点,m条边
void Dij()
{

    for (int x = 1; x <= n; x++)//保证每个点都被遍历到
    {
        int mmin = inf;
        int t=1;
        for (int i = 1; i <= n; i++)//找到一个距离第一个点最近的点
        {
            if (!vis[i] && dist[i] < mmin)
            {
                mmin = dist[i];
                t = i;
            }
        }
        vis[t] = true;
        for (int i = 1; i <= n; i++)//看其他点是否可以借助这个点来缩短到第一个点的距离
        {
            if (dist[i] > dist[t] + paths[i][t])
            {
                dist[i] = dist[t] + paths[i][t];
            }
        }
    }
    
}
int main()
{
    cin >> n >> m;
    //初始化paths数组
    memset(paths, inf, sizeof(paths));
    for (int i = 1; i <= n; i++)
        paths[i][i] = 0;
    for (int i = 1; i <= m; i++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        paths[u][v] = w;
        paths[v][u] = w;
        
    }
    //初始化距离数组
    for (int i = 1; i <= n; i++)
    {
        dist[i] = paths[i][1];
    }
    //初始化vis数组
    memset(vis, false, sizeof(vis));
    vis[1] = true;
    Dij();

    //输出每个点到第一个点的最短距离
    for (int i = 1; i <= n; i++)
    {
        cout << dist[i] << " ";
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值