16. 要在8×8的国际象棋棋盘中放8个皇后,使任意两个皇后都不能互相吃掉。规则:皇后能吃掉同一行、同一列、同一对角线的任意棋子。编程求方案数。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int count = 0;
// 检查当前位置是否安全
bool isSafe(int board[], int row, int col, int n) {
for (int i = 0; i < row; i++) {
// 检查列冲突和对角线冲突
if (board[i] == col || abs(board[i] - col) == abs(i - row)) {
return false;
}
}
return true;
}
// 回溯算法
void solveNQueens(int board[], int row, int n) {
if (row == n) {
count++;
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
board[row] = col; // 放置皇后
solveNQueens(board, row + 1, n);
// 回溯
board[row] = -1;
}
}
}
int main() {
int n;
scanf("%d", &n);
int board[n];
for (int i = 0; i < n; i++) {
board[i] = -1; // 初始化棋盘
}
solveNQueens(board, 0, n);
printf("%d\n", count);
return 0;
}
运行结果:
17. n个作业{1,2,…,n}要在由2台机器M1和M2组成的流水线上完成加工。每个作业加工的顺序都是先在M1上加工,然后在M2上加工。M1和M2加工作业i所需的时间分别为ai和bi。流水作业调度问题要求确定这n个作业的最优加工顺序,使得从第一个作业在机器M1上开始加工,到最后一个作业在机器M2上加工完成所需的时间最少。
#include <stdio.h>
#define MAX_N 100
int min(int a, int b) {
return (a < b) ? a : b;
}
int minMakespan(int n, int a[], int b[]) {
int dp[MAX_N + 1][2]; // dp[i][0] and dp[i][1] for i = 0 to n
dp[0][0] = 0;
dp[0][1] = a[0] + b[0];
for (int i = 1; i <= n; ++i) {
dp[i][0] = min(dp[i-1][0] + a[i-1], dp[i-1][1] + a[i-1]);
dp[i][1] = min(dp[i-1][0] + a[i-1] + b[i-1], dp[i-1][1] + b[i-1]);
}
return min(dp[n][0], dp[n][1]);
}
int main() {
int n;
printf("Enter the number of jobs (n): ");
scanf("%d", &n);
int a[MAX_N], b[MAX_N];
printf("Enter the processing times for machine M1 (a array):\n");
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
printf("Enter the processing times for machine M2 (b array):\n");
for (int i = 0; i < n; ++i) {
scanf("%d", &b[i]);
}
int min_time = minMakespan(n, a, b);
printf("Minimum makespan for scheduling the jobs: %d\n", min_time);
return 0;
}
运行结果:
结语
生命太过短暂
今天放弃了明天不一定能得到
!!!