A. Round House 模拟

A. Round House
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.

Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If b = 0, then Vasya prefers to walk beside his entrance.

Illustration for n = 6a = 2b =  - 5.

Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.

Input

The single line of the input contains three space-separated integers na and b (1 ≤ n ≤ 100, 1 ≤ a ≤ n,  - 100 ≤ b ≤ 100) — the number of entrances at Vasya's place, the number of his entrance and the length of his walk, respectively.

Output

Print a single integer k (1 ≤ k ≤ n) — the number of the entrance where Vasya will be at the end of his walk.

Examples
input
6 2 -5
output
3
input
5 1 3
output
4
input
3 2 7
output
3
Note

The first example is illustrated by the picture in the statements.


直接模拟正向反向走路,可以一步一步模拟,数据很水,暴力直接过;

#include <stdio.h>
#include <algorithm>
int a[1000005] , b[1000005];
int main() {
	int n , m;
	int t = 0, k = 0;
	scanf("%d%d",&n,&m);
	for(int i = 0; i < n; i++) {
		scanf("%d",&a[i]);
	}
	std::sort(a,a+n);
	for(int i = 1; ; i++) {
		if(i == a[k]) {
			k++;
			continue;
		}
		if(m >= i) {
			m -= i;
			b[t++] = i;
		}
		else break;
	}
	printf("%d\n",t);
	for(int i = 0; i < t; i++) {
		printf("%d ",b[i]);
	}
	printf("\n");
	return 0;
}




<think>嗯,用户让我介绍一下如何完成生成房价数据、加载数据、定义模型、训练模型以及可视化的整个过程。首先,我需要分步骤来思考每个任务的具体实现方法。 任务一是生成房价数据并保存为Excel。我需要考虑生成五个特征和一个目标值。房屋面积、房间数量、楼层、房龄、地理位置评分这些特征的数据分布。比如,房屋面积可能是正态分布,房间数量和楼层可能是整数,房龄可能有一定的范围,地理位置评分可能是1到10的整数。目标值房价应该是这些特征的线性组合加上一些噪声。然后,用pandas生成DataFrame,保存到Excel。 接下来是数据加载,需要从Excel读取,并转换为PyTorch张量。可能需要对数据进行标准化处理,特别是不同量纲的特征,比如房屋面积可能比房龄大很多,标准化可以加速训练。但用户标注为可选,所以可能需要提到两种情况的处理方式。 定义模型部分,使用nn.Linear,输入特征数是5,输出是1。需要初始化模型,并可能需要设置学习率等超参数。 损失函数和优化器部分,均方误差损失和Adam优化器是标准的,这部分应该直接使用PyTorch内置的函数。 训练模型的话,需要循环多次epoch,每次前向传播计算损失,反向传播前要梯度清零,然后参数更新。可能需要设定合适的epoch次数和学习率,这里用户没给具体数值,可以给示例值如1000次,学习率0.01。 可视化部分,损失曲线可以用matplotlib绘制,真实值与预测值的对比图可以用散点图,看它们是否接近对角线。 现在,需要检查是否有遗漏的步骤,比如数据分割为训练集和测试集?用户没提到,可能不需要。但通常在机器学习中会这样做,不过根据任务描述,可能直接使用全部数据训练。所以可能不需要拆分。 另外,生成数据时要确保各特征之间的相关性合理,比如房屋面积大可能房间数量多,但用户可能希望各特征独立生成,所以暂时不考虑相关性,用随机生成的方式,但加入线性组合生成房价。 在代码实现时,需要注意数据类型转换,比如生成整数特征时,用astype(int),然后将数据转换为float32的Tensor,因为PyTorch通常使用float32。 标准化处理部分,可能需要用sklearn的StandardScaler,或者手动计算均值和标准差。但如果是可选的话,可以展示如何做,并说明好处。 在模型定义时,要确认输入输出的维度是否正确。多元线性回归是输入5个特征,输出1个值,所以nn.Linear(5,1)。 训练过程中,需要将输入数据和目标值都转换为Tensor,并且可能需要设置requires_grad=False,或者让模型自动处理。优化器要传入模型的参数。 可视化的时候,需要从Tensor转换回numpy数组,因为matplotlib不能直接处理Tensor。 还要注意保存Excel时不要包含索引列,读取时正确加载各列。 现在,把这些步骤用中文清晰地组织起来,确保代码正确,并解释每个部分的作用。可能需要提示用户安装必要的库,如pandas, torch, matplotlib。 检查是否有可能的错误,比如生成数据时的列名是否正确,模型的前向传播是否正确,损失函数是否计算正确,反向传播和优化步骤是否正确。特别是梯度清零optimizer.zero_grad()这一步不能漏掉。 总结来说,整个流程需要按照任务分步骤解释,提供可运行的代码示例,并说明关键点,比如数据生成、标准化、模型定义、训练循环和可视化方法。</think>以下分步骤实现房价预测的多元线性回归模型开发流程: --- ### 任务一:生成房价数据(完整实现) ```python import pandas as pd import numpy as np # 生成1000条样本数据 np.random.seed(42) n_samples = 1000 data = { # 正态分布特征 '房屋面积': np.random.normal(120, 30, n_samples).round(1), # 均值120㎡,标准差30 # 整数特征 '房间数量': np.random.randint(1, 6, n_samples), '楼层': np.random.randint(1, 31, n_samples), # 均匀分布 '房龄': np.random.uniform(0, 50, n_samples).round(1), # 评分特征 '地理位置评分': np.random.randint(1, 11, n_samples), } # 生成房价目标值(加入噪声) coefficients = np.array([8000, 50000, 2000, -1000, 10000]) # 各特征系数 noise = np.random.normal(0, 50000, n_samples) # 噪声项 data['房价'] = np.dot(pd.DataFrame(data).values, coefficients) + noise # 保存为Excel df = pd.DataFrame(data) df.to_excel('house_prices.xlsx', index=False) print("数据已保存至house_prices.xlsx") ``` --- ### 任务二:数据加载与处理 ```python import torch import pandas as pd from sklearn.preprocessing import StandardScaler # 读取数据 df = pd.read_excel('house_prices.xlsx') # 分离特征和标签 X = df.drop('房价', axis=1).values y = df['房价'].values.reshape(-1,1) # 数据标准化(可选但推荐) scaler_X = StandardScaler() scaler_y = StandardScaler() X_scaled = scaler_X.fit_transform(X) y_scaled = scaler_y.fit_transform(y) # 转换为PyTorch张量 X_tensor = torch.tensor(X_scaled, dtype=torch.float32) y_tensor = torch.tensor(y_scaled, dtype=torch.float32) ``` --- ### 任务三:定义模型 ```python import torch.nn as nn class LinearRegression(nn.Module): def __init__(self, input_dim): super().__init__() self.linear = nn.Linear(input_dim, 1) def forward(self, x): return self.linear(x) model = LinearRegression(input_dim=5) print(model) ``` --- ### 任务四:定义损失与优化器 ```python criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) ``` --- ### 任务五:训练模型 ```python epochs = 1000 losses = [] for epoch in range(epochs): # 前向传播 outputs = model(X_tensor) loss = criterion(outputs, y_tensor) # 反向传播 optimizer.zero_grad() loss.backward() optimizer.step() # 记录损失 losses.append(loss.item()) if (epoch+1) % 100 == 0: print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}') ``` --- ### 任务六:可视化与结果 ```python import matplotlib.pyplot as plt # 损失曲线 plt.figure(figsize=(12,5)) plt.subplot(1,2,1) plt.plot(losses) plt.title('Training Loss') plt.xlabel('Epoch') plt.ylabel('MSE') # 预测对比 with torch.no_grad(): predictions = model(X_tensor).numpy() predictions = scaler_y.inverse_transform(predictions) y_true = scaler_y.inverse_transform(y_tensor) plt.subplot(1,2,2) plt.scatter(y_true, predictions, alpha=0.5) plt.plot([y_true.min(), y_true.max()], [y_true.min(), y_true.max()], 'r--') plt.xlabel('True Prices') plt.ylabel('Predicted Prices') plt.title('Prediction vs True Value') plt.tight_layout() plt.show() ``` --- ### 关键实现说明: 1. **数据生成**:通过设置不同分布模拟真实数据特征,加入线性关系和噪声项 2. **标准化处理**:使用`StandardScaler`消除量纲差异,提升模型收敛速度 3. **模型结构**:单层线性层实现多元线性回归,输入维度与特征数量一致 4. **训练技巧**:使用Adam优化器自适应调整学习率,定期清空梯度防止累积 5. **结果解读**:通过损失曲线观察收敛情况,对比图应接近对角线为理想状态 实际应用中可根据需要调整数据生成参数、模型超参数(学习率、epoch数)和可视化细节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值