gym 100947I (求因子)

本文介绍了一种算法问题,即给定一系列齿轮齿数,如何找出所有满足倍数关系的齿轮对数量。通过预处理和排序,利用因子查找的方法来避免重复计算。

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

    What a Mess

Alex is a very clever boy, after all he is the son of the greatest watchmaker in Odin.

One day, Alex was playing with some old watches and he found n gears, each gear has ai teeth in it. Alex likes to make beautiful pairs of gears, he thinks a pair of gears is beautiful if we attach the two gears together and spin the first gear exactly one rotation, then the other gear spins an integer number of rotations. For example a pair of 8 and 4 is beautiful, whereas a pair of 8 and 5 isn't, neither is pair of 4and 8.

Now Alex is curious, he wants to know how many beautiful pairs are there. Counting is not Alex's thing, so he asked you to help him.

Input

The first line of input contains one integer T: The number of test cases you need to process.

Each test case consists of two lines. The first line is a single integer n: the number of gears Alex has. The second line contains n space separated integers ai: the number if teeth in the ith gear.

1 ≤ n ≤ 104

2 ≤ ai ≤ 106

Output

For each testcase print a single integer: the number of distinct pairs that satisfy the problem statement.

Examples
input
2
5
4 6 7 8 12
6
2 2 2 3 3 4
output
3
7
Note

note that we consider two pair distinct when they differ by at least one gear.

In the first sample the pairs are: (4,8) , (4,12) , (6,12)

题意:

  如果两个数是倍数关系,那么他们就是beautiful,问有多少对beautiful。

思路:

  对于一个数,只求他的每个因子在序列中有几个就可以了,这样就不会重复,注意要先排序,不然有些会计算不到。

代码:

/** @xigua */
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<cstring>
#include<queue>
#include<set>
#include<string>
#include<map>
#include<climits>
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef double db;
const int maxn = 1e6 + 5;
const int mod = 1e9 + 7;
const int INF = 1e8 + 5;
const ll inf = 1e15 + 5;
const db eps = 1e-9;
int vis[maxn];
int a[maxn];

void solve() {
    memset(vis, 0,sizeof(vis));
    int n; cin >> n;
    ll ans = 0;
    for (int i = 1; i <= n; i++) {
        scanf("%d", a + i);
    }
    sort(a+1, a+1+n);
    for (int i = 1; i <= n; i++) {
        int x = a[i];
        for (int j = 1; j * j <= x; j++) {
            if (x % j == 0) {   //是因子
                ans += vis[j];  // 看该因子出现过几次
                int xx = x / j;
                if (xx != j) {
                    ans += vis[xx]; //另一个不同因子,因为因子是成对出现的
                }
            }
        }
        vis[x]++;   //先计算后标记
    }
    cout << ans << endl;
}

int main() {
    //cin.sync_with_stdio(false);
    //freopen("isharp.in", "r", stdin);
    //freopen("isharp.out", "w", stdout);
    int t = 1; cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/ost-xg/p/6398868.html

### 结合 Gym 和 PyTorch 进行强化学习开发 在 Python 中结合 Gym 和 PyTorch 开发强化学习模型是一种常见的实践方式。以下是关于如何利用这些工具构建强化学习系统的详细介绍。 #### 1. 使用 Gym 构建环境 Gym 是 OpenAI 提供的一个用于开发和比较强化学习算法的工具包。它提供了多种预定义的环境,可以模拟不同的场景。如果需要自定义环境,则可以通过继承 `gym.Env` 类来创建自己的环境[^1]。 ```python import gym env = gym.make('CartPole-v1') # 创建一个简单的 CartPole 环境作为例子 observation = env.reset() # 初始化环境并获取初始观察值 ``` #### 2. 定义神经网络结构 PyTorch 是一个强大的深度学习框架,支持动态计算图,非常适合用来设计复杂的神经网络架构。对于强化学习中的策略函数或价值函数近似器,可以选择全连接层或其他更高级别的模块。 下面是一个基本的两层全连接前馈神经网络的例子: ```python import torch import torch.nn as nn class PolicyNetwork(nn.Module): def __init__(self, input_dim, output_dim): super(PolicyNetwork, self).__init__() self.fc1 = nn.Linear(input_dim, 64) self.fc2 = nn.Linear(64, output_dim) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.softmax(self.fc2(x), dim=-1) return x ``` 此代码片段展示了如何定义一个具有两个隐藏层的小型神经网络,该网络接受输入维度大小为 `input_dim` 的数据,并输出概率分布向量表示可能的动作选择[^2]。 #### 3. 实现强化学习训练循环 为了完成整个流程,在每一步都需要从环境中采样当前状态下的动作,然后执行这个动作得到新的状态、奖励以及其他信息;接着更新参数以优化目标函数(通常是累计折扣回报)。这里展示了一个简化版的过程概述: ```python from collections import deque import random def train(env, policy_net, optimizer, episodes=500): gamma = 0.99 # 折扣因子 max_steps_per_episode = 1000 for episode in range(episodes): state = env.reset() done = False rewards = [] log_probs = [] while not done: state_tensor = torch.tensor(state).float().unsqueeze(0) action_probabilities = policy_net(state_tensor) distribution = torch.distributions.Categorical(action_probabilities) action = distribution.sample() next_state, reward, done, _ = env.step(action.item()) rewards.append(reward) log_probs.append(distribution.log_prob(action)) state = next_state if len(log_probs) >= max_steps_per_episode or done: break discounts = [(gamma ** i) * r for i, r in enumerate(rewards)] R = sum(discounts[::-1]) / (len(rewards)) # 计算总收益 loss = (-sum([lp*R for lp in log_probs])) # 负对数似然乘以期望收益即为目标损失 optimizer.zero_grad() loss.backward() optimizer.step() policy_network = PolicyNetwork(env.observation_space.shape[0], env.action_space.n) optimizer = torch.optim.Adam(policy_network.parameters(), lr=0.01) train(env, policy_network, optimizer) ``` 上述脚本实现了基于 REINFORCE 方法的基础版本,其中包含了完整的训练逻辑。 #### 多智能体扩展思考 当涉及多个代理时,可以根据具体需采用不同类型的 MARL 方案。例如,若希望保持各智能体之间的独立性同时允许一定程度的合作,则可选用混合式方法[^3]。此时需要注意调整共享经验回放缓冲区的设计或者引入额外的消息传递机制以便于协调各个个体的行为模式。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值