W - Period


Time Limit: 3000MS Memory Limit: 30000KB 64bit IO Format: %I64d & %I64u

[Submit]   [Go Back]   [Status]

Description

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A K ,that is A concatenated K times, for some string A. Of course, we also want to know the period K.

Input

The input consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S.The second line contains the string S. The input file ends with a line, having the 
number zero on it.

Output

For each test case, output "Test case #" and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.

Sample Input

3
aaa
12
aabaabaabaab
0

Sample Output

Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4
 
  
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;
#define MAXN 1000010
int next[MAXN];
char s[MAXN];
int len;

void get_next()
{
	int i=0;
	int j=-1;
	next[0]=-1;
	while(i<len)
	{
		if(j==-1||s[i]==s[j])
		{
			i++;j++;
			next[i]=j;		//这里如果改用另外一种形式写:if(s[i]!=s[j])
							//								next[i]=next[j];
							//							  else next[i]=j;
							//为什么就不行呢?这里理解不够深刻啊;
		}
		else j=next[j];
	}
}

int main()
{
	int n;
	int i;
	int count=0;
	while(scanf("%d",&n)!=EOF&&n)
	{
		count++;
		scanf("%s",s);
		len=strlen(s);
		get_next();
		printf("Test case #%d\n",count);
		for( i=2;i<=len;i++)
		if((i%(i-next[i]))==0)
         {
             int t=i/(i-next[i]);
             if(t>1)
             printf("%d %d\n",i,t);
         } 
         printf("\n");
     }
	return 0;
}


//+------------------------------------------------------------------+ //| TrendFollowingEA.mq5 | //| Copyright 2023, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2023, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" #property strict input double LotSize = 0.01; // 基础交易手数 input double GridStep = 0.3; // 加仓间隔(点) input int LookbackBars = 100; // 指标计算回溯周期 // 全局变量 double lastBuyPrice = 0; // 最后开仓价格 int positionCount = 0; // 持仓数量 double lastTrendLine = 0; // 上一根K线的多空线值 double prevTrendLine = 0; // 上上一根K线的多空线值 bool trendUp = false; // 当前趋势是否向上 //+------------------------------------------------------------------+ //| EA初始化函数 | //+------------------------------------------------------------------+ int OnInit() { // 初始化历史数据 if(Bars(_Symbol, _Period) < LookbackBars + 10) { Print("Not enough historical data"); return(INIT_FAILED); } // 计算初始多空线值 lastTrendLine = CalculateTrendLine(1); // 上一根K线 prevTrendLine = CalculateTrendLine(2); // 上上一根K线 return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| EA反初始化函数 | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { } //+------------------------------------------------------------------+ //| EA主函数 | //+------------------------------------------------------------------+ void OnTick() { // 获取当前K线的多空线值 double currentTrendLine = CalculateTrendLine(0); // 判断趋势方向变化 bool newTrendUp = false; bool newTrendDown = false; // 趋势转为向上(拐头向上) if(currentTrendLine > lastTrendLine && lastTrendLine < prevTrendLine) { newTrendUp = true; } // 趋势转为向下(拐头向下) if(currentTrendLine < lastTrendLine && lastTrendLine > prevTrendLine) { newTrendDown = true; } // 趋势转为向上 - 开首单 if(newTrendUp && !trendUp) { if(OpenBuyOrder()) { trendUp = true; lastBuyPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); // 记录开仓价格 } } // 当前处于上涨趋势 if(trendUp) { double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); // 双向加仓逻辑:价格波动达到网格间距 if(MathAbs(currentPrice - lastBuyPrice) >= GridStep * _Point) { if(OpenBuyOrder()) { lastBuyPrice = currentPrice; // 更新最后开仓价格 } } // 趋势转为向下 - 平掉所有多单 if(newTrendDown) { CloseAllBuyPositions(); trendUp = false; positionCount = 0; lastBuyPrice = 0; } } // 更新多空线历史值 prevTrendLine = lastTrendLine; lastTrendLine = currentTrendLine; } //+------------------------------------------------------------------+ //| 计算多空线指标 | //+------------------------------------------------------------------+ double CalculateTrendLine(int barIndex) { // 计算TR1: 真实波幅的最大值 double high = iHigh(_Symbol, _Period, barIndex); double low = iLow(_Symbol, _Period, barIndex); double prevClose = iClose(_Symbol, _Period, barIndex + 1); double tr1 = MathMax(high - low, MathMax(MathAbs(prevClose - high), MathAbs(prevClose - low))); // APR: TR1的1期移动平均(实际上就是TR1本身) double apr = tr1; // 中价 double median = (high + low) / 2.0; // 计算HH和LL double HH = median + apr; double LL = median - apr; // 计算W值 int barsSinceHH = -1; int barsSinceLL = -1; // 寻找最近一次HH >= HHV(HH,10)的位置 for(int i = barIndex; i < barIndex + LookbackBars; i++) { // 计算当前K线的HH double currentHigh = iHigh(_Symbol, _Period, i); double currentLow = iLow(_Symbol, _Period, i); double currentPrevClose = iClose(_Symbol, _Period, i + 1); double currentTR1 = MathMax(currentHigh - currentLow, MathMax(MathAbs(currentPrevClose - currentHigh), MathAbs(currentPrevClose - currentLow))); double currentMedian = (currentHigh + currentLow) / 2.0; double currentHH = currentMedian + currentTR1; // 计算HHV(HH,10) double hhv = currentHH; for(int j = i; j < MathMin(i + 10, Bars(_Symbol, _Period) - 1); j++) { double tempHigh = iHigh(_Symbol, _Period, j); double tempLow = iLow(_Symbol, _Period, j); double tempPrevClose = iClose(_Symbol, _Period, j + 1); double tempTR1 = MathMax(tempHigh - tempLow, MathMax(MathAbs(tempPrevClose - tempHigh), MathAbs(tempPrevClose - tempLow))); double tempHH = (tempHigh + tempLow) / 2.0 + tempTR1; if(tempHH > hhv) hhv = tempHH; } // 检查条件 if(currentHH >= hhv) { barsSinceHH = i - barIndex; break; } } // 寻找最近一次LLV(LL,5) >= LL的位置 for(int i = barIndex; i < barIndex + LookbackBars; i++) { // 计算当前K线的LL double currentHigh = iHigh(_Symbol, _Period, i); double currentLow = iLow(_Symbol, _Period, i); double currentPrevClose = iClose(_Symbol, _Period, i + 1); double currentTR1 = MathMax(currentHigh - currentLow, MathMax(MathAbs(currentPrevClose - currentHigh), MathAbs(currentPrevClose - currentLow))); double currentMedian = (currentHigh + currentLow) / 2.0; double currentLL = currentMedian - currentTR1; // 计算LLV(LL,5) double llv = currentLL; for(int j = i; j < MathMin(i + 5, Bars(_Symbol, _Period) - 1); j++) { double tempHigh = iHigh(_Symbol, _Period, j); double tempLow = iLow(_Symbol, _Period, j); double tempPrevClose = iClose(_Symbol, _Period, j + 1); double tempTR1 = MathMax(tempHigh - tempLow, MathMax(MathAbs(tempPrevClose - tempHigh), MathAbs(tempPrevClose - tempLow))); double tempLL = (tempHigh + tempLow) / 2.0 - tempTR1; if(tempLL < llv) llv = tempLL; } // 检查条件 if(llv >= currentLL) { barsSinceLL = i - barIndex; break; } } // 如果未找到符合条件的K线,使用默认值 if(barsSinceHH == -1) barsSinceHH = LookbackBars; if(barsSinceLL == -1) barsSinceLL = LookbackBars; // 计算W值 int W = barsSinceHH - barsSinceLL; // 计算BBX和SSX double BBX = EMPTY_VALUE; double SSX = EMPTY_VALUE; // 计算BBX = LLV(H, BARSLAST(W<0)) if(W > 0) { int startBar = barIndex + barsSinceLL; BBX = iHigh(_Symbol, _Period, startBar); for(int i = startBar; i <= barIndex; i++) { double highVal = iHigh(_Symbol, _Period, i); if(highVal < BBX) BBX = highVal; } } // 计算SSX = HHV(L, BARSLAST(W>0)) else if(W < 0) { int startBar = barIndex + barsSinceHH; SSX = iLow(_Symbol, _Period, startBar); for(int i = startBar; i <= barIndex; i++) { double lowVal = iLow(_Symbol, _Period, i); if(lowVal > SSX) SSX = lowVal; } } // 计算多空线 double trendLine; if(W > 0) trendLine = BBX; else if(W < 0) trendLine = SSX; else trendLine = iClose(_Symbol, _Period, barIndex); return trendLine; } //+------------------------------------------------------------------+ //| 开多单 | //+------------------------------------------------------------------+ bool OpenBuyOrder() { MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = LotSize; request.type = ORDER_TYPE_BUY; request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); request.deviation = 5; request.type_filling = ORDER_FILLING_FOK; if(OrderSend(request, result)) { positionCount++; Print("Buy order opened. Price: ", request.price, " Lots: ", LotSize); return true; } else { Print("Buy order failed. Error: ", GetLastError()); return false; } } //+------------------------------------------------------------------+ //| 平掉所有多单 | //+------------------------------------------------------------------+ void CloseAllBuyPositions() { int total = PositionsTotal(); for(int i = total - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket > 0 && PositionSelectByTicket(ticket)) { if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; request.position = ticket; request.symbol = _Symbol; request.volume = PositionGetDouble(POSITION_VOLUME); request.deviation = 5; request.type_filling = ORDER_FILLING_FOK; request.type = ORDER_TYPE_SELL; request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); if(OrderSend(request, result)) { Print("Position closed: ", ticket); } else { Print("Failed to close position ", ticket, ". Error: ", GetLastError()); } } } } } 以上代码修改一下,打开允许EA算法交易按钮就开始按照指令进行交易
最新发布
12-16
### F-W-H 平行趋势检验方法概述 F-W-H 平行趋势检验是一种用于评估处理组和对照组在干预前是否存在显著差异的方法,通常应用于双重差分模型(Difference-in-Differences, DiD)分析中。该检验的核心在于验证两组数据的趋势是否一致,从而判断政策或实验效果的有效性和合理性。 #### 统计假设 在进行平行趋势检验时,原假设通常是:处理组和对照组在干预之前的趋势相同。如果拒绝这一假设,则表明可能存在其他混杂因素影响结果,需重新审视研究设计。 --- ### 方法描述 F-W-H 平行趋势检验可以通过回归分析来实现。具体而言,在干预时间之前的时间点上逐步加入虚拟变量及其交互项,观察这些系数是否显著偏离零。以下是其实现的关键步骤: 1. **构建面板数据集** 面板数据应包含个体单位(如公司、地区)、时间维度以及处理状态指示器。设 \( D_i \) 表示第 \( i \) 个个体是否属于处理组;\( T_t \) 是时间哑变量,表示特定时间段的状态。 2. **设定回归方程** 考虑如下形式的线性回归模型: \[ Y_{it} = \alpha + \beta_1 D_i + \sum_{t=-k}^{-1} (\gamma_t D_i \times T_t) + X'_{it}\delta + \epsilon_{it} \] 其中, - \( Y_{it} \): 第 \( i \) 个个体在时间 \( t \) 的因变量; - \( D_i \): 处理组指示变量; - \( T_t \): 时间哑变量,取值范围为干预前若干期至干预当期; - \( X'_{it} \): 控制变量集合; - \( \gamma_t \): 关键参数,衡量每期相对于基期的变化幅度。 3. **解释估计结果** 如果所有前期交互项系数均不显著异于零,则支持平行趋势假定成立。反之,若某些系数显著,则可能暗示存在预冲击效应或其他偏差[^3]。 --- ### Python 实现代码 以下是一个简单的Python实现案例,利用 `statsmodels` 库完成上述过程: ```python import pandas as pd import numpy as np import statsmodels.api as sm from statsmodels.formula.api import ols # 假设我们有一个面板数据框 df,其中包含以下列: # 'y': 因变量 # 'id': 单位ID # 'time': 时间索引 # 'treated': 是否为处理组 (0/1) # 'post': 是否处于干预后时期 (0/1) def fwh_parallel_test(df): # 创建干预前各时期的虚拟变量并与 treated 变量相乘 periods_before = [-3, -2, -1] # 定义干预前几期 for period in periods_before: col_name = f"pre{abs(period)}" df[col_name] = np.where((df['time'] == period), 1, 0) * df['treated'] # 构建回归公式字符串 formula = "y ~ treated" for period in periods_before: formula += f" + pre{abs(period)}" # 添加控制变量(如果有) control_vars = ['control_var1', 'control_var2'] # 替换为实际使用的控制变量名 if control_vars: formula += " +" + "+".join(control_vars) # 运行 OLS 回归 model = ols(formula=formula, data=df).fit() print(model.summary()) return model.params, model.pvalues # 示例调用函数 params, pvals = fwh_parallel_test(your_dataframe_here) ``` 此脚本会生成一系列关于干预前不同阶段的统计测试结果,并帮助识别潜在问题所在。 --- ### 注意事项 尽管通过回归可以有效执行平行趋势检验,但在实践中还需注意以下几个方面: - 数据质量直接影响结论可靠性; - 若样本规模较小或者分布极不平衡,可能导致标准误过高而难以得出稳健推断; - 对异常值敏感,建议提前清理极端观测值后再运行正式分析。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值