【算法实验】——二分分治、回溯法、分支界限、动态DP

本文包括:

实验1,求解查找假币问题

实验4,求解满足方程解问题

实验2,求解布线问题

实验9,求解相邻比特数问题


实验1,求解查找假币问题

编写一个实验程序查找假币问题。有n(n>3)个硬币,其中有一个假币,且假币较轻,

采用天平称重方式找到这个假币,并给出操作步骤。

【思路】

#include <iostream>
using namespace std;
#define N 1000

// 求重量和
int SUM(int weight[], int m, int n) {
int sum = 0;
for (int i = m; i <= n; i++) {
sum += weight[i];
}
return sum;
}

int solution(int weight[], int left, int right) {
// 先判定再递归
if (right - left == 1)
return weight[right] > weight[left] ? left : right;
if (right == left)
return right;
int mid = (right + left) / 2;

// 硬币数量为奇数个数时
if ((right - left) % 2 == 0) {
int lw = SUM(weight, left, mid - 1);
int rw = SUM(weight, mid + 1, right);
return (lw == rw) ? mid : (lw > rw ? solution(weight, mid + 1, right) : solution(weight, left, mid - 1));
}
// 硬币为偶数个数时
else if ((right - left) % 2 == 1) {
int lw = SUM(weight, left, mid);
int rw = SUM(weight, mid + 1, right);
return (lw > rw) ? solution(weight, mid + 1, right) : solution(weight, left, mid);
}
}

int main() {
int n;
int weight[N] = { 0 };
cout << "【请输入硬币的个数:】" << endl;
if (!(cin >> n) || n <= 3 || n > N) {
cout << "输入的硬币数量无效,请重新运行程序并输入有效的硬币数量。" << endl;
return 1;
}
cout << "【请输入各个硬币的重量】" << endl;
for (int i = 0; i < n; i++) {
cout << "第" << i + 1 << "个硬币的重量是:>";
if (!(cin >> weight[i]) || weight[i] < 0) {
cout << "输入的硬币重量无效,请重新运行程序并输入有效的硬币重量。" << endl;
return 1;
}
}
int sz = solution(weight, 0, n - 1);
cout << endl << "第" << sz + 1 << "个是假币!" << endl;
return 0;
}

【运行结果】


 实验4,求解满足方程解问题

编写一个实验程序,求出a、b、c、d、e,满足ab-cd-e=1方程,其中所有变量的取值为1~5 并且均不相同。

方法一:暴力枚举

#include <iostream>

using namespace std;

bool is_valid(int a, int b, int c, int d, int e)
{
    return (a *  b - c *  d - e) == 1;
}

void find_solution()
{
    for (int a = 1; a <= 5; a++) {
        for (int b = 1; b <= 5; b++) {
            if (b != a) {
                for (int c = 1; c <= 5; c++) {
                    if (c != a && c != b) {
                        for (int d = 1; d <= 5; d++) {
                            if (d != a && d != b && d != c) {
                                for (int e = 1; e <= 5; e++) {
                                    if (e != a && e != b && e != c && e != d) {
                                        if (is_valid(a, b, c, d, e)) {
                                            cout << a << " " << b << " " << c << " " << d << " " << e << endl;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

int main()
{
    find_solution();
    return 0;
}

【方法二——利用next_permutation函数生成全排列】

#include <iostream>
#include <algorithm>

using namespace std;

bool is_valid(int a, int b, int c, int d, int e)
{
    return (a *  b - c *  d - e) == 1;
}

void find_solution()
{
    int nums[] = {1, 2, 3, 4, 5};

    do {
        int a = nums[0];
        int b = nums[1];
        int c = nums[2];
        int d = nums[3];
        int e = nums[4];

        if (is_valid(a, b, c, d, e)) {
            cout << a << " " << b << " " << c << " " << d << " " << e << endl;
        }
    } while (next_permutation(nums, nums + 5));
}

int main()
{
    find_solution();
    return 0;
}

方法三——回溯法

#include <iostream>

using namespace std;

bool used[6] = {false}; // 标记数字是否被使用过
int nums[5];            // 存储当前的排列

bool is_valid(int a, int b, int c, int d, int e)
{
    return (a * b - c * d - e) == 1;
}

void backtrack(int k)
{
    if (k == 5) {
        int a = nums[0];
        int b = nums[1];
        int c = nums[2];
        int d = nums[3];
        int e = nums[4];

        if (is_valid(a, b, c, d, e)) {
            cout << a << " " << b << " " << c << " " << d << " " << e << endl;
        }
        return;
    }

    for (int i = 1; i <= 5; i++) {
        if (!used[i]) {
            used[i] = true;
            nums[k] = i;
            backtrack(k + 1);
            used[i] = false;
        }
    }
}

int main()
{
    backtrack(0);
    return 0;
}

【运行结果】

​​​​​​​​​​​​​​


实验2,求解布线问题

印制电路板将布线区域划分成nXm个方格。精确的电路布线问题要求确定连接方格a的中点到方格6的中点的最短布线方案。在布线时,电路只能沿直线或直角布线。为了避免线路相交,对已布了线的方格做了封锁标记,其他线路不允许穿过被封锁的方格。

图6.15所示为一个布线的例子,图中阴影部分是指被封锁的方格,其起始点为a、目标点为b。编写一个实验程序采用分枝限界法求解。

代码

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

struct Position {
int x;
int y;
};

const int MAX_N = 102;
int grid[MAX_N][MAX_N];
int n, m;

bool FindPath(Position start, Position finish, vector<Position>& path) {
if (start.x == finish.x && start.y == finish.y) {
return true;
}

for (int j = 0; j <= m + 1; j++) {
grid[0][j] = 1;
}
for (int i = 0; i <= n + 1; i++) {
grid[i][0] = 1;
}
for (int j = 0; j <= m + 1; j++) {
grid[n + 1][j] = 1;
}
for (int i = 0; i <= n + 1; i++) {
grid[i][m + 1] = 1;
}

Position offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int NumOfNbrs = 4;
Position now, neighbor;
now = start;
grid[start.x][start.y] = 0;
queue<Position> Q;
Q.push(now);

while (!Q.empty()) {
now = Q.front();
Q.pop();

for (int i = 0; i < NumOfNbrs; i++) {
neighbor.x = now.x + offset[i].x;
neighbor.y = now.y + offset[i].y;

if (grid[neighbor.x][neighbor.y] == 0) {
grid[neighbor.x][neighbor.y] = grid[now.x][now.y] + 1;
path[neighbor.x * (m + 2) + neighbor.y] = now;

if (neighbor.x == finish.x && neighbor.y == finish.y) {
return true;
}
Q.push(neighbor);
}
}
}

return false;
}

void PrintShortestPath(Position start, Position finish, vector<Position>& path) {
Position curr = finish;
vector<Position> shortestPath;

// 从终点往起点回溯,构造最短路径
while (!(curr.x == start.x && curr.y == start.y)) {
shortestPath.push_back(curr);
curr = path[curr.x * (m + 2) + curr.y];
}
shortestPath.push_back(start);

// 倒序打印最短路径
for (int i = shortestPath.size() - 1; i >= 0; i--) {
cout << "(" << shortestPath[i].x << "," << shortestPath[i].y << ") ";
}
}

int main() {
cout << "请输入电路板的行数,列数:" << endl;
cin >> n >> m;

Position start, finish;
cout << "请输入起始坐标:" << endl;
cin >> start.x >> start.y;
cout << "请输入终点坐标:" << endl;
cin >> finish.x >> finish.y;
cout << "请用0/1表示障碍图:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> grid[i][j];
}
}

vector<Position> path((n + 2) * (m + 2));
if (FindPath(start, finish, path)) {
cout << "【测试结果】" << endl;
cout << "最短路径:";
PrintShortestPath(start, finish, path);
cout << endl;
cout << "路径长度:" << grid[finish.x][finish.y] << endl;
} else {
cout << "【测试结果】" << endl;
cout << "无法找到路径" << endl;
}

return 0;
}

【运行结果】


实验9,求解相邻比特数问题

【问题描述】

一个n位的01字符串x = x1x2…xn,其相邻比特数由函数:fun(x) = x1x2 + x2x3 + … + xn - 1xn 计算出来,它计算两个相邻的1出现的次数。比如:

fun(011101101) = 3

fun(111101101) = 4

fun(010101010) = 0

编写程序以n和p作为输入,求出长度为n的满足fun(x) = p的x的个数。例如,n = 5, p = 2的结果为6,即x有11100, 01110, 10111, 11101和11011。

【输入描述】

第一个整数n,第二个整数为p

【输入样例】

5 2

【输出描述】

输出要求的个数

【输出样例】

6

代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int CountAdjacentOnes(string x) {
int count = 0;
for (int i = 0; i < x.length() - 1; i++) {
if (x[i] == '1' && x[i + 1] == '1') {
count++;
}
}
return count;
}

void GenerateBinaryStrings(int n, string x, int p, int& count) {
if (n == 0) {
if (CountAdjacentOnes(x) == p) {
count++;
}
return;
}
GenerateBinaryStrings(n - 1, x + '0', p, count);
GenerateBinaryStrings(n - 1, x + '1', p, count);
}

int main() {
int n, p;
cin >> n >> p;

int count = 0;
string x = "";
GenerateBinaryStrings(n, x, p, count);

cout << count << endl;

return 0;
}

【运行结果】


如果觉得本文有帮助到你的话:不妨点个赞支持一下吧~点个关注也是可以的啰~

我们下期再见👋

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值