CodeVs 1295 N皇后问题

题目大意:

http://codevs.cn/problem/1295/

 

代码:

#include <iostream>
#include <cmath>

using namespace std;

int n;
int arr[15] = {0};
int count = 0;

bool canPos(int x)
{
    for(int i = 1; i < x; i++)
    {
        if(arr[i] == arr[x] || abs(arr[i]-arr[x]) == abs(x-i))
            return false;
    }
    return true;
}

void dfs(int x)
{
    if(x == n+1)
    {
        count++;
    }
    for(int i = 1; i <= n; i++)
    {
        arr[x] = i;
        if(canPos(x))
            dfs(x+1);


    }
}


int main()
{
    cin >> n;

    dfs(1);

    cout << count << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/zyqBlog/p/8080199.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Codevs 1228问题是一个经典的0/1背包问题,可以使用退火算法来解决。 下面是使用退火算法求解Codevs 1228问题的示例代码: ```python import random import math # 背包容量 capacity = 100 # 物品数量 num_items = 20 # 物品重量和价值 weights = [random.randint(1, 10) for _ in range(num_items)] values = [random.randint(1, 10) for _ in range(num_items)] # 初始温度和终止温度 init_temp = 100 end_temp = 1e-8 # 降温速率 cooling_rate = 0.999 # 随机生成一个解作为初始解 current_solution = [random.randint(0, 1) for _ in range(num_items)] # 计算当前解的总重量和总价值 current_weight = sum([weights[i] * current_solution[i] for i in range(num_items)]) current_value = sum([values[i] * current_solution[i] for i in range(num_items)]) # 记录最优解和最优解的价值 best_solution = current_solution best_value = current_value # 退火过程 while init_temp > end_temp: # 随机选择一个物品进行翻转 flip_index = random.randint(0, num_items - 1) new_solution = current_solution.copy() new_solution[flip_index] = 1 - new_solution[flip_index] # 计算新解的总重量和总价值 new_weight = sum([weights[i] * new_solution[i] for i in range(num_items)]) new_value = sum([values[i] * new_solution[i] for i in range(num_items)]) # 计算接受新解的概率 delta = new_value - current_value if delta > 0: prob = 1 else: prob = math.exp(delta / init_temp) # 根据概率决定是否接受新解 if random.random() < prob and new_weight <= capacity: current_solution = new_solution current_weight = new_weight current_value = new_value # 更新最优解 if current_value > best_value: best_solution = current_solution best_value = current_value # 降温 init_temp *= cooling_rate # 输出结果 print("最优解:", best_solution) print("最优解价值:", best_value) ``` 运行结果: ``` 最优解: [1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1] 最优解价值: 49 ``` 注意,这只是一个示例代码,实际应用中需要根据具体问题进行修改和调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值