CF984C Finite or not?

CodeForces C题解析
本文解析了CodeForces C题“Finite or not?”的算法思路及实现细节,阐述了如何通过判断分数在特定进制下的有限性来解决该问题。

原题链接:http://codeforces.com/contest/984/problem/C

Finite or not?

You are given several queries. Each query consists of three integers p,q p , q and b b . You need to answer whether the result of p/q in notation with base b b is a finite fraction.

A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.

Input

The first line contains a single integer n(1n105) n ( 1 ≤ n ≤ 10 5 ) — the number of queries.

Next n n lines contain queries, one per line. Each line contains three integers p,q, and b(0p1018,1q1018,2b1018) b ( 0 ≤ p ≤ 10 18 , 1 ≤ q ≤ 10 18 , 2 ≤ b ≤ 10 18 ) . All numbers are given in notation with base 10 10 .

Output

For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.

Examples
input

2
6 12 10
4 3 10

output

Finite
Infinite

input

4
1 1 2
9 36 2
4 12 3
3 5 4

output

Finite
Finite
Finite
Infinite

Note

612=12=0,510 6 12 = 1 2 = 0 , 5 10

43=1,(3)10 4 3 = 1 , ( 3 ) 10

936=14=0,012 9 36 = 1 4 = 0 , 01 2

412=13=0,13 4 12 = 1 3 = 0 , 1 3

题解

先约一波分,如果 q q 的质因数都是b的因数,那么 pq p q b b 进制下就是有限的。

但是值域是1018,直接分解质因数肯定血 T T ,所以我们每次直接除以gcd(q,b)就可以将 q q b共有的质因子除掉,我们这样一直除下去直到 gcd(b,q)=1 g c d ( b , q ) = 1 q=1 q = 1 时就可以判定了,如果 q=1 q = 1 输出 Finite F i n i t e ,否则输出 Infinite I n f i n i t e

另外还有一个优化, b b 如果有q没有的质因数对结果是不影响的,可以直接将 b b 设为gcd(q,b)

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
void in(){scanf("%d",&n);}
void ac()
{
    ll p,q,b,g;
    while(n--)
    {
        scanf("%lld%lld%lld",&p,&q,&b);
        for(q/=gcd(p,q),g=gcd(q,b);g!=1&&q!=1;b=g,q/=g,g=gcd(q,b));
        q==1?puts("Finite"):puts("Infinite");
    }
}
int main(){in();ac();}
import numpy as np import pandas as pd class FeatureStreamHealth: def __init__(self, z_thresholds=(2.0, 4.0), ewma_alpha=None, robust_q_point=0.99, use_mad=True, persist_points=3, weights=None): """ 健康评估器,基于特征流(RMS, STD, PEAK, KURT, CF, MEAN) 工况只有 axis = x/y/z 三个方向 """ self.T_low, self.T_high = z_thresholds self.ewma_alpha = ewma_alpha self.robust_q_point = robust_q_point self.use_mad = use_mad self.persist_points = persist_points # 默认权重:能量 0.45,冲击 0.40,偏置 0.15 self.weights = weights or { 'RMS': 0.20, 'STD': 0.15, 'PEAK': 0.10, 'KURT': 0.20, 'CF': 0.20, 'MEAN': 0.15 } self.baselines = {} # dict[axis] -> dict[feature] -> (mu, sigma) @staticmethod def mad(arr): med = np.median(arr) return np.median(np.abs(arr - med)) @staticmethod def robust_clip(arr, q): upper = np.quantile(arr, q) return np.clip(arr, None, upper) def build_baseline(self, df, feature_cols): """ 用健康数据建立基线 df 必须包含列 ['axis'] + feature_cols """ grouped = df.groupby(['axis'], dropna=False) for axis, g in grouped: baseline = {} for k in feature_cols: vals = g[k].to_numpy(dtype=float) vals = vals[np.isfinite(vals)] if k in ['PEAK', 'KURT', 'CF']: vals = self.robust_clip(vals, q=self.robust_q_point) if len(vals) < 50: continue if self.use_mad and k in ['RMS', 'STD']: mu = float(np.median(vals)) sigma = float(self.mad(vals) * 1.4826) else: mu = float(np.mean(vals)) sigma = float(np.std(vals)) sigma = sigma if sigma > 1e-12 else 1.0 baseline[k] = (mu, sigma) if baseline: self.baselines[axis] = baseline def z_scores(self, feats_dict, baseline, feature_cols): z = {} for k in feature_cols: mu, sigma = baseline[k] val = float(feats_dict[k]) z[k] = (val - mu) / sigma return z def penalty(self, z_val): return float(np.clip((z_val - self.T_low) / (self.T_high - self.T_low), 0.0, 1.0)) def score_from_z(self, z_dict): P = 0.0 for k, w in self.weights.items(): P += w * self.penalty(z_dict[k]) score = 100.0 * (1.0 - P) return max(0.0, min(100.0, score)), P def evaluate_points(self, df, feature_cols, segment_id_col=None): """ 点级评估:对每个特征点计算分数与告警 df 必须包含 ['timestamp','axis'] + feature_cols """ rows = [] ewma_states = {} for axis, g in df.groupby(['axis'], dropna=False): if axis not in self.baselines: continue baseline = self.baselines[axis] g_sorted = g.sort_values('timestamp') for _, row in g_sorted.iterrows(): feats = {k: float(row[k]) for k in feature_cols} if self.ewma_alpha is not None: st = ewma_states.get(axis, {k: feats[k] for k in feature_cols}) for k in feature_cols: st[k] = self.ewma_alpha * feats[k] + (1 - self.ewma_alpha) * st[k] ewma_states[axis] = st feats = st z = self.z_scores(feats, baseline, feature_cols) score, P = self.score_from_z(z) rows.append({ 'axis': axis, 'timestamp': row['timestamp'], 'segment_id': row[segment_id_col] if segment_id_col and segment_id_co l in df.columns else None, 'score': score, **{f'{k}': float(row[k]) for k in feature_cols}, **{f'z_{k}': float(z[k]) for k in feature_cols} }) return pd.DataFrame(rows) def summarize_segments(self, point_df, segment_id_col='segment_id'): """ 段级汇总:对同一段的点级结果做中位汇总与再评分 """ if segment_id_col not in point_df.columns: return None def segment_score(group): score_med = float(group['score'].median()) z_cols = [c for c in group.columns if c.startswith('z_')] z_med = {c: float(group[c].median()) for c in z_cols} P = 0.0 for k, w in self.weights.items(): zk = z_med.get(f'z_{k}', 0.0) p = np.clip((zk - self.T_low) / (self.T_high - self.T_low), 0.0, 1.0) P += w * p score_refined = max(0.0, min(100.0, 100.0 * (1.0 - P))) return pd.Series({ 'segment_score_median': score_med, 'segment_score_refined': score_refined, 'point_count': len(group) }) return point_df.groupby([segment_id_col, 'axis'], dropna=False).apply(segment_score).reset_index() 这是我的所有代码 帮我详细讲解一下基线构造函数并详细讲解一下里面涉及到的语法 函数 和变量 参数
最新发布
12-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值