CF#344 div2 C.Report(思维)

Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i+1, or directly to Blake (if this manager has number i=m).

Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.

Input

The first line of the input contains two integers n and m (1≤n,m≤200000)− the number of commodities in the report and the number of managers, respectively.

The second line contains n integers ai (|ai|≤109)− the initial report before it gets to the first manager.

Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (, 1≤rin), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti=1) or non-ascending (if ti=2) order.

Output

Print n integers− the final report, which will be passed to Blake by manager number m.

Examples

Input

3 1
1 2 3
2 2

Output

2 1 3 

Input

4 2
1 2 4 3
2 3
1 2

Output

2 4 1 3 

Note

In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.

In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.

题目大意:给出n个数,m个操作。输入a,b,a为操作种类,b为操作位置。2种操作——1.1到b从小到大排序,2.从1到b从大到小排序。最后输出最终操作后的数组。

思路:直接模拟是不可能过的,妥妥的超时。所以需要思考如何缩减操作,若操作位置大于上一个操作的位置,那之前的操作都会被覆盖掉,所以可以从这一点入手。标记每一个操作的时间线与操作位置。可以考虑用2个数组存。例如:

 

 

第一个输出的数组是操作的时间线,第二个输出的是操作类型,第三个输出的是最终操作后的数组。可以看出,最后时间线最大的会覆盖掉之前操作位置比它小的操作。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=200010;
int p[maxn];//数组 
int num[maxn];//数组 
int s1[maxn];//操作时间  
int s2[maxn];//操作类型 
int main()
{
    int n,m;cin>>n>>m;
    for(int i=1;i<=n;++i)
	{
        scanf("%d",&num[i]);
    }
    int a,b;
    for(int i=1;i<=m;i++) 
	{
        scanf("%d%d",&a,&b);
        s1[b]=i;s2[b]=a;//s1记录对当前的数的操作的最晚的一次s2记录操作的类型
    }
    for(int i=1;i<=n;i++) printf("%d ",s1[i]);printf("\n");
	for(int i=1;i<=n;i++) printf("%d ",s2[i]);printf("\n"); 
    int F=1,R=n,nowoper,now=0;
    for(int i=n;i>=1;i--)
	{
        if(s2[i]==0)  p[i]=num[i];//未操作的直接保存 
        else 
		{
            R=i;break;//找到被操作的最大位置 
        }
    }
    sort(num+1,num+R+1);//对操作过的数排序便于操作赋值 
    for(int i=R;i>=1;i--)
	{
        if(s2[i]==1&&s1[i]>now)//判断对当前的数的操作的顺序是否大于前一个数如果大于则记录对此数的操作类型
		{
            now=s1[i];//位置 
            nowoper=s2[i];//类型 
        }
        if(nowoper==1)//从小到大,保存继续 
		{
            p[i]=num[R];R--;
        }
        else 
		{
            p[i]=num[F];F++;//从大到小(倒着赋值) 
        }
    }
    for(int i=1;i<=n;++i)
	{
        if(i==n)  printf("%d\n",p[i]);
        else   printf("%d ",p[i]);
    }
    return 0;
}

 

import requests from lxml import etree import csv import time import random import re import os from scrapy import Selector # 固定请求头配置(需替换为实际值) FIXED_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0' FIXED_COOKIE = 'll="118161"; bid=l5ki4SOlbBM; dbcl2="244638424:dLHXPIU8S0M"; push_noty_num=0; push_doumail_num=0; __utmv=30149280.24463; _pk_id.100001.4cf6=42b01014d5c31947.1748938983.; _vwo_uuid_v2=D9E78C6D9D4E71BBB6EC73B8583864961|9da3be87da4a6d3be6203809b085d4a9; __yadk_uid=2Zr6yzTnllQxMzDhrQB82h7doa8gM4Ku; ck=ILlj; ap_v=0,6.0; frodotk_db="dcae91cc1eae6af7960bb5645c0b40e5"; __utma=30149280.1697373246.1748938900.1750132184.1750207462.10; __utmc=30149280; __utmz=30149280.1750207462.10.7.utmcsr=cn.bing.com|utmccn=(referral)|utmcmd=referral|utmcct=/; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1750207469%2C%22https%3A%2F%2Fwww.douban.com%2F%22%5D; _pk_ses.100001.4cf6=1; __utma=223695111.238348316.1748938983.1750132184.1750207469.10; __utmb=223695111.0.10.1750207469; __utmc=223695111; __utmz=223695111.1750207469.10.8.utmcsr=douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmt=1; __utmb=30149280.6.10.1750207462' # 需从浏览器获取 # 基础URL和请求头 base_url = "https://movie.douban.com/subject/27181010/reviews" headers = { 'User-Agent': FIXED_USER_AGENT, 'Cookie': FIXED_COOKIE, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Referer': 'https://movie.douban.com/subject/27181010/', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-User': '?1', } # 创建输出目录 os.makedirs('douban_data', exist_ok=True) # 创建CSV文件并写入表头 csv_file = open('douban_data/douban_reviews_fixed(4).csv', 'w', newline='', encoding='utf-8-sig') writer = csv.writer(csv_file) writer.writerow(['昵称', '星级评分', '评论时间', '文本评论', '点赞数', '负赞数', '回应数', '页面位置']) def extract_content(element): """提取评论内容,处理展开情况""" # 尝试提取短评内容 short_content = element.xpath('.//div[contains(@class, "short-content")]/text()') if short_content: return ''.join(short_content).strip() # 尝试提取完整评论内容 full_content = element.xpath('.//div[@class="review-content clearfix"]/text()') if full_content: return ''.join(full_content).strip() # 尝试提取折叠内容 folded_content = element.xpath('.//div[@class="folded"]/text()') if folded_content: return ''.join(folded_content).strip() return "无内容" # 爬取多页数据 for page in range(0, 125): # 构造URL参数 params = { 'start': page * 20, 'sort': 'new_score', 'status': 'P' } try: print(f"开始爬取第 {page+1} 页...") # 发送请求(禁止重定向以检测验证) response = requests.get( url=base_url, params=params, headers=headers, timeout=15, allow_redirects=False # 禁止重定向以检测验证 ) # 检查重定向状态码(302表示需要验证) if response.status_code == 302: location = response.headers.get('Location', '未知位置') print(f"⚠️ 第 {page+1} 页触发验证,重定向至: {location}") # 保存重定向页面供分析 with open(f'douban_data/redirect_page_{page}.html', 'w', encoding='utf-8') as f: f.write(response.text) continue response.encoding = 'utf-8' if response.status_code == 200: # 解析HTML html = etree.HTML(response.text) # 检查是否有验证码提示 captcha = html.xpath('//input[@name="captcha-id"]') if captcha: print(f"⚠️ 第 {page+1} 页需要验证码,跳过") # 保存验证码页面供分析 with open(f'douban_data/captcha_page_{page}.html', 'w', encoding='utf-8') as f: f.write(response.text) continue # 检查页面是否包含评论容器(使用更灵活的选择器) review_container = html.xpath('//div[@class="review-list"]') if not review_container: # 尝试备用选择器 review_container = html.xpath('//div[contains(@id, "content")]//div[contains(@class, "review")]') if not review_container: # 保存异常页面用于分析 with open(f'douban_data/error_page_{page}.html', 'w', encoding='utf-8') as f: f.write(response.text) print(f"❌ 第 {page+1} 页无评论容器,已保存页面供分析") continue # 提取评论项(更新后的选择器) comments = html.xpath('//div[contains(@class, "review-item")]') # 备用选择器:尝试抓取评论项 if not comments: comments = html.xpath('//div[contains(@class, "main") and contains(@class, "review-item")]') if not comments: comments = html.xpath('//div[@class="review-list"]/div[contains(@class, "review")]') if not comments: print(f"❌ 第 {page+1} 页找到0条评论,可能触发反爬") # 检查反爬提示 anti_spider = html.xpath('//div[contains(text(), "检测到异常请求")]') if anti_spider: print("⚠️ 检测到反爬提示,请更换Cookie或IP") # 保存页面供分析 with open(f'douban_data/antispider_page_{page}.html', 'w', encoding='utf-8') as f: f.write(response.text) continue print(f"✅ 第 {page+1} 页找到 {len(comments)} 条评论") for idx, comment in enumerate(comments): try: # 提取昵称 username = comment.xpath('.//a[contains(@class, "name")]/text()') if not username: username = comment.xpath('.//span[@class="author"]/a/text()') username = username[0].strip() if username else "无昵称" # 提取星级评分 rating = comment.xpath('.//span[contains(@class, "rating")]/@title') if not rating: rating = comment.xpath('.//span[contains(@class, "main-title-rating")]/@title') rating = rating[0] if rating else "无评分" # 提取评论时间 comment_time = comment.xpath('.//span[contains(@class, "main-meta")]/text()') # 提取文本评论 content = extract_content(comment) # 提取点赞数 selector_list = comment.xpath('.//*[contains(@id, "useful_count")]/text()') if selector_list: # 检查列表是否非空 raw_text = selector_list[0] else: raw_text = "" # 空结果处理 match = re.search(r'\d+', raw_text) useful_count = int(match.group()) if match else 0 # 提供默认值 # 提取负赞数 selector_list = comment.xpath('.//*[contains(@id, "useless_count")]/text()') if selector_list: # 检查列表是否非空 raw_text = selector_list[0] else: raw_text = "" # 空结果处理 match = re.search(r'\d+', raw_text) useless_count = int(match.group()) if match else 0 # 提供默认值 # 提取回应数 reply_count = comment.xpath('.//*[contains(@id, "reply")]/text()') # 写入CSV writer.writerow([ username, rating, comment_time, content, useful_count, useless_count, reply_count, f"第{page+1}页第{idx+1}条" ]) except Exception as e: print(f"⚠️ 处理评论时出错: {e}") continue else: print(f"❌ 请求失败,状态码: {response.status_code}") except Exception as e: print(f"❌ 请求异常: {e}") # 随机延迟,避免频繁请求 delay = random.uniform(3, 8) print(f"⏳ 等待 {delay:.2f} 秒后继续...") time.sleep(delay) csv_file.close() print("✅ 爬取完成!数据已保存到 douban_data/douban_reviews_fixed(4).csv"),此代码在爬取文本评论时无法爬取未展开的评论内容,帮我修改代码,使得可以爬取相对应的完整评论内容,此外,提取回应数的输出为[],其Xpath样式为//*[@id="16724545"]/div/div[3]/a[3],帮我修改,要修改后的所有完整代码
06-19
我想用stm32f407让大疆m2006转起来 请帮我看看代码有没有什么问题 如果有该怎么改/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "can.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "CAN_receive.h" #include "bsp_can.h" #include "pid.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ pid_type_def motor_pid; extern PID_TypeDef drive_motor_pid[4]; const motor_measure_t *motor_data[4]; int set_speed = 0; const fp32 PID[3] = {10,0.02,0}; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_CAN1_Init(); /* USER CODE BEGIN 2 */ can_filter_init(); for (int di = 0;di<4;di++) { pid_init(&drive_motor_pid[di]); drive_motor_pid [di].f_param_init(&drive_motor_pid[di],PID_Speed,16384,5000,10,0,8000,0,10,0.02,0); } motor_data[0] = get_chassis_motor_measure_point(0); motor_data[1] = get_chassis_motor_measure_point(1); motor_data[2] = get_chassis_motor_measure_point(2); motor_data[3] = get_chassis_motor_measure_point(3); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ drive_motor_pid[0].target=5000; drive_motor_pid[1].target=5000; drive_motor_pid[0].f_cal_pid(&drive_motor_pid[0],motor_data[0]->speed_rpm); drive_motor_pid[1].f_cal_pid(&drive_motor_pid[0],motor_data[1]->speed_rpm); drive_motor_pid[2].f_cal_pid(&drive_motor_pid[0],motor_data[2]->speed_rpm); drive_motor_pid[3].f_cal_pid(&drive_motor_pid[0],motor_data[3]->speed_rpm); CAN_cmd_chassis(drive_motor_pid[0].output, drive_motor_pid[1].output, drive_motor_pid[2].output, drive_motor_pid[3].output); HAL_Delay(2); /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 8; RCC_OscInitStruct.PLL.PLLN = 168; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 4; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */
最新发布
07-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值