1.8万

SE6_02
Jysir_
ice_
uuuzi
Explainaur
QBJ
invisible-pat.
Sunny9
MangataTS

Cabin-65--
zedchou
RyuJeXu
1024M

Hanasaki

Douglas_4

class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int ans=1e9,t=0;
for(int i=0,j=0; i<nums.size(); i++){
t+=nums[i];
while(t>=target){
ans=min(abs(i-j+1),ans);
t-=nums[j++];
}
}
return ans==1e9?0:ans;

}
};


#include <iostream>
using namespace std;
int n;
const int N=1e5+10;
int INF=1e9+10;
int a[N];
int main(){
cin>>n;
for(int i=0; i<n; i++){
scanf("%*d %d",&a[i]);
}
int minx=INF,ans=0;
for(int i=n-1; i>=0; i--){
if(a[i]<=minx){
ans++;
minx=a[i];
}
}
cout<<ans;
return 0;
}


#include <iostream>
#include <queue>
using namespace std;
const int N=1e6+10;
int a[N];
queue<int>q;
int n,k;
int main(){
cin>>n>>k;
while(n--){
int a1,a2;
cin>>a1>>a2;
a[a2]=a1;
}
int t=0,ans=0;
for(int i=0; i<N; i++){
if(q.size()>k*2){
t-=q.front();
q.pop();
}
q.push(a[i]);
t+=a[i];
ans=max(ans,t);
}
cout<<ans;

return 0;
}


B站教学链接 点击进入

1.首先学会get、post请求和封装

所需要的包
import urllib.request
import urllib.parse

res=urllib.request.urlopen("http://www.baidu.com")
res=urllib.request.urlopen("http://www.baidu.com")

import  urllib.parse
data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
res =urllib.request.urlopen("http://httpbin.org/post",data=data)

try:
response =urllib.request.urlopen("http://httpbin.org/get",timeout=0.01)
except urllib.error.URLError as e:
print("time out")
res =urllib.request.urlopen("http://www.baidu.com",timeout=1)

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
}
data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
url="http://httpbin.org/post"
res =urllib.request.urlopen(req)

import urllib.request
import urllib.parse
url="https://www.douban.com"
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",
}
res=urllib.request.urlopen(req)


2.目标html的解析与搜索

import re

from bs4 import BeautifulSoup
file =open("./uniapp.html","rb")#二进制读取，把文件读取到内存里面
bs=BeautifulSoup(html,"html.parser")#解析html文档

print(type(bs.title))#拿到标签及其内容（第一个）
print(bs.a)
print(bs.title.string)#标签里的内容
print(bs.name)#整个文档

#文档的遍历
#(都是按标签找)

#文档的搜索

find_all()
#字符串过滤：会查找与字符串完全匹配的内容
t_list=bs.find_all("a")

#正则表达式搜索：使用search()方法来匹配内容
import  re
t_list=bs.find_all(re.compile("a"))

#方法：传入一个函数，根据函数的要求来搜索
def name_is_exists(tag):
return tag.has_attr("id")
t_list=bs.find_all(name_is_exists)

for item in t_list:
print(item)
print(t_list)

# #kwargs参数
t_list =bs.find_all(id="app")
t_list =bs.find_all(class_=True)
#t_list=bs.find_all(class_="dfs")
for item in t_list:
print(item)

#test参数
t_list =bs.find_all(text=["第一个","第二个"])
t_list =bs.find_all(text=re.compile("\d"))#应用正则表达式来查找包含特定文本内容内容（标签里的字符串）

#limit参数
t_list =bs.find_all("a",limit=3)
for item in t_list:
print(item)

#css选择器
t_list=bs.select("title")#通过标签
t_list=bs.select(".dfs")#通过内容
t_list=bs.select("#u1")#通过id来查找
t_list=bs.select("a[class='dfs']")#通过属性来查找
t_list=bs.select("div>a")#通过子标签
for item in t_list:
print(item.get_text())

#正则表达式


3.正则表达式：字符串模式（判断字符串是否符合一定的标准）

import re
#创建模式对象
pat=re.compile("AA")#此处的AA是一个正则表达式，用来验证其他的字符串
m=pat.search("AAAAAAAAAAAAAAAAABAA")#search方法进行比对查找

#没有模式对象
m=re.search("asd","Aasd")
print(m)
m=re.findall("[a-z]+","lsaAk3jdfla")
print(m)
#sub
print(re.sub("a","asdfasdf","lajfas")) #找到a用A来替换

#建议在正则表达式中，被比较的字符串前面加上r,不用担心转义字符问题
a=r"\naabd\sdf"
print(a)


4.爬取豆瓣电影top250实战

所需要的包
from bs4 import BeautifulSoup         #网页解析获取数据
import re           #正则表达式
import urllib.request,urllib.error  #制定url,获取网页数据
import xlwt         #进行excel制作
import sqlite3      #进行SQLITE数据库操作
def main():
baseurl="https://movie.douban.com/top250?start="
#1爬取网页
datalist=getData(baseurl)

savepath=r".\豆瓣电影TOP350.xls"

#3保存数据
saveData(savepath)
#<a href="https://movie.douban.com/subject/1292052/">
#<img alt="肖申克的救赎" class="" src="https://img2.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg" width="100"/>
findImgSrc=re.compile(r'<img alt.*src="(.*?)"" width="100"/>',re.S)#让换行符包含在字符中
findTitle=re.compile(r'<span class="title">(.*?)</span>',re.S)
findRating=re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>',re.S)
findJudge=re.compile(r'<span>(%d*)人评价</span>')
findInq=re.compile(r'<span class="inq">(.*)</span>')
findBp=re.compile(r'<p class="">(.*)</p>')
#爬取网页
def getData(baseurl):
datalist=[]
for i in range(0,1):           #调用获取页面信息的函数10次
url=baseurl + str(i*25)

#2逐一解析数据
soup=BeautifulSoup(html,"html.parser")
for item in soup.find_all('div',class_="item"):
#print(item)
data=[] #保存一部电影的所有信息
item=str(item)

#获取到影片详情的超链接
imgSrc=re.findall(findImgSrc,item)[0]
data.append(imgSrc)
title=re.findall(findTitle,item)
if(len(title)==2)
ctitle=title[0]
data.append(ctitle)

return datalist

#得到制定一个URL的网页内容
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",

}#用户代理，表示告诉豆瓣服务器，我们是什么类型的机器-浏览器（本质上是告诉浏览器我们可以接收什么水平的文件内容）
html=""
try:
res=urllib.request.urlopen(req)

except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html

#保存数据
def saveData(savepath):
print("djf")

if __name__ == "__main__":  #当程序执行时
main()
#调用函数


B站教学链接 点击进入

Python语法

#输出
print("dlkjfs");
a=10
age=18;
print("sdfs %d dlfj"%age);
print("dfj%s %s"%("小张","dfjd"))

print("aaa","bbb","kkk")
print("www","baidu","com",sep=".")

print("hello",end="")
print("hello",end="\t")
print("hello",end="\n")

'''
'''
#输入

a=input("lsdjfs")
print(type(a))
a=int("123")
int()#强制类型转化
b=a+100
print(b)

'''
'''
#判断
if True:
print("ldjf")
else :
print("fjdslf")
import random
x=random.randint(0,2)#随机数
print(x)

#循环
for i in range(5):
print(i);
for i in range(0,14,3):#从0开始到13结束
print(i)

name="chengdu"
for x in name:
print(x,end=' ')

a=["aa","bb","cc"]
for i in range(len(a)):
print(a[i])

i=0
while i<5:
print("当前第几次%d"%(i+1))
print("i=%d"%i)#注意是百分号
i+=1

i=1
sum=0
while i<=100:
sum+=i;
i+=1
print(sum)

count=10
while count<5:
print(count,"xiaoyu5")
count+=1
else:
print(count,"大于或对于5")
break
continue

for i in range(1,10,1):
print(\t)
for j in range(1,i+1,1):
print(%d*%d=%d %(i,j,i*j),end=\t)

for x in range(1, 10):
print(\t)
for y in range(1, x + 1):
result = x * y
print( % d * % d = % d % (x, y, x * y), end =\t)

for m in range(1,10):
for n in range(1,10):
if m n:
print(%s*%s=%s%(m,n,m*n),end= \t)
elif m == n:
print(%s*%s=%s%(m,n,m*n),end=\n)

for i in range(1, 10, 1):
for j in range(1, i + 1, 1):
print("%d*%d=%d" % (j, i, i * j), end=" ")
print('\t')

#字符串
word ='字符串'
sentence ="sehsdfsdf"
paragraph="""sdfjlsdfjs
dsfsdljkf
"""
print(word)
print(sentence)
print(paragraph)

my_str='dlfj\'d'
print(my_str)

my_str="Jason sair\"dsf\""
print(my_str)
str="chengdu"
print(str)
print(str[0:5])
print(str[1:7:2])#起始位置：结束位置：步进值
print(str[1:])
print(str[:5])
print(str*10+",dkjfd"*3)
print(r"hello\ndfdf")#r能取消\号效果

namelist=[545,"xdjfkd","小李"]
#print(type(namelist[0]))

for i in namelist:
print(type(len(namelist)))

i=0
while i<len(namelist):
print(namelist[i])
i+=1

#增
for name in namelist:
print(name)
nametemp=input()
namelist.append(nametemp)

for name in namelist:
print(name)

a=[1,2]
b=[3,4]
a.append(b)#将列表当作一个元素
print(a)

a.extend(b)
print(a)#将b列表元素，全部加入

a=[0,1,2]
a.insert(1,3)  #第一个是下标，第二个是元素
print(a)

#删
m=["1111","2222","3333","4444","5555"]
for i in m:
print(i)
del m[2]
m.pop()
m.remove("1111")#只删除第一个
for i in m:
print(i)

#改
m=["1111","2222","3333","4444","5555"]
for i in m:
print(i)
print("-------------------")
m[1]="xioahong"

for i in m:
print(i)

#查
m=["1111","2222","3333","4444","5555"]
findname=input()

if findname in m:
print("找打")
else :
print("没有")

a=["a","b","c","a","b"]
#print(a.index("a",0,4))#可以查找指定下标范围元素，返回指定下标(范围区间为左闭右开) 找不到报错
print(a.count("a"))

#排序
a=[1,4,2,3]
print(a)
a.reverse()
print(a)
a.sort(reverse=True)
print(a)

import  random
s =[["a","b"],["c","d"],["e","f"]]
print(s[0][0])
for name in s:
index=random.randint(0,2)
s[index].append(name)
for a in s:
print()

#元组
t=("sdf","kldsf",2020,2021,333)
t2=(50,)
print(t[0:5])#左闭右开

#增(连接)
t=(12,23,34,45)
t2=("ldfj","ldsjf")
t=t+t2
print(t)

#删
t=(12,23,34)
print(t)
del tup
print(t)

#字典 dict
a={"name":"dkfj","age":18}#定义
print(a["age"])
print(a.get("sdlfj"))#没有找到返回none（默认）
print(a.get("dsfj","hhh"))
print(a.get("age","20"))

#增
a={"name":"dkfj","age":18}#定义
newID=input()
a["id"]=newID
print(a["id"])

#删
a={"name":"dkfj","age":18}#定义
print("%s"%a["name"]+"a"*10)
del a["name"]

a={"name":"dkfj","age":18}#定义
print("%s"%a)
#del a
#claer 清空
a.clear()
print(a)

#改
a={"name":"dkfj","age":18}#定义
a["age"]=1223
print(a["age"])

#查(遍历)
a={"name":"wang","age":18}#定义
print(a.keys())
print(a.values())
print(a.items())

for key in  a.keys():
print(key)
for value,key in a.items():
print("%s  %s"%(key,value))

mylist=["a","c","b"]
print(enumerate(mylist))
#使用枚举函数同时拿到下标内容
for i,x in enumerate(mylist):
print(i,x)

#集合set
#去重

#函数
def printa():
print("-"*10)
print("test")
print("-"*10)

#printa()
c=a+b
print(c)

return a+b

print(res)

def divid(a,b):
shang=a//b
yushu=a%b
return shang,yushu
sh,yu=divid(5,2)   #多个返回值
print("%d  %d"%(sh,yu));

a=100
def test1():
global a#global
a=300
print(a)

def test2():
a=200
print(a)

test1()
test2()
print(a)

#文件
f=open("test.txt","w")#打开文件
f.close()  #关闭文件

f=open("test.txt","w")
f.write("lsdjfkdsljfs")
f.close()
#读取指定的字符，开始读头部，往后依次读
f=open("test.txt","r")#打开文件
print(c)
print(c1)

f.close()

f=open("test.txt","r")#打开文件
print(c)
i=1
for t in c:
print("%d:%s"%(i,t))
i+=1
f.close()

import os
os.rename("test01.txt","test.txt")

#异常
#捕获异常
try:
#print("-test"*10)
f=open("123.txt","r");
print(name)
print("-"*10)#不会执行
except (NameError,IOError,SyntaxError)as result:
print("错误")         #捕获异常执行代码
print(result)

try:
#print("-test"*10)
f=open("123.txt","r");
print(name)
print("-"*10)#不会执行
except Exception as result:
print("错误")         #捕获异常执行代码
print(result)

# try finally 和嵌套
import time

try:
f = open("test.txt", "r")
try:
while True:
if (len(c)) == 0:
break
time.sleep(2)
print(c)
finally:
f.close()
print("文件关闭")

except Exception as result:
print("发生异常")


#include <iostream>
#include <queue>
using namespace std;
const int N=1000010;
int n,k,a;
queue<int>q;
int p[N];
int main(){
cin>>n>>k;
int ans=-1,t=0;
for(int i=0; i<n; i++){
cin>>a;
if(p[a]!=0)ans=max(ans,a);
p[a]++;
q.push(a);
t++;
if(t>k){
p[q.front()]--;
q.pop();
}
}
cout<<ans;
}



#include <iostream>
#include <algorithm>
using namespace std;
int n;
const int INF=1e8,N=1e5+1;
#define x first
#define y second
typedef pair<int,int> PII;
int smax[N],smin[N];
PII a[N];
int main(){
cin>>n;
for(int i=1; i<=n; i++){
cin>>a[i].x>>a[i].y;
}
sort(a+1,a+n+1);
smax[0]=-INF,smin[n+1]=INF;
for(int i=1; i<=n; i++)smax[i]=max(smax[i-1],a[i].y);
for(int i=n; i; i--)smin[i]=min(smin[i+1],a[i].y);
int ans=0;
for(int i=1; i<=n; i++){
if(smax[i-1]<a[i].y&&smin[i+1]>a[i].y)ans++;
}
cout<<ans;
}


#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=1010;
bool st[N][N],g[N][N];
int dist[N][N];

int bfs(int sx,int sy){
deque<PII>q;
q.push_back({sx,sy});
memset(dist,0x3f,sizeof dist);
dist[sx][sy]=0;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
while(q.size()){
auto t=q.front();
q.pop_front();
if(st[t.x][t.y])continue;
st[t.x][t.y]=true;
if(!t.x&&!t.y)break;

for(int i=0; i<4; i++){//扩展
int x=t.x+dx[i],y=t.y+dy[i];
if(x>=0&&x<N&&y>=0&&y<N){
int w=0;
if(g[x][y])w=1;
if(dist[x][y]>dist[t.x][t.y]+w){//更新距离
dist[x][y]=dist[t.x][t.y]+w;
if(!w)q.push_front({x,y});
else q.push_back({x,y});
}
}
}
}
return dist[0][0];
}

int main(){
int n,sx,sy;
cin>>n>>sx>>sy;
while(n--){
int x, y;
cin>>x>>y;
g[x][y]=true;
}
cout<<bfs(sx,sy);
return 0;
}


#include <iostream>
#include <map>
using namespace std;
map<int,int>b;
int n;
int main(){
int a,x=0;
char c;
cin>>n;
for(int i=0; i<n; i++){
cin>>a>>c;
if(c=='R'){
b[x]++;
b[x+a-1+1]--;
x+=a;
}else{
b[x-1+1]--;
b[x-a]++;
x-=a;
}
}
int ans=0,last,sum=0;
for(auto& [a,s] : b){
if(sum>=2){
ans+=abs(a-last);
}
sum+=s;
last=a;
}
cout<<ans;
return 0;
}


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int N=1e5+10;
string a[N],b[N],c[N];
int n;
int main(){
cin>>n;
for(int i=1; i<=n; i++){
cin>>a[i];
b[i]=c[i]=a[i];
sort(b[i].begin(),b[i].end(),greater<int>());
sort(c[i].begin(),c[i].end());
}
sort(b+1,b+n+1);
sort(c+1,c+n+1);
for(int i=1; i<=n; i++){
sort(a[i].begin(),a[i].end());
string s=a[i];
int l=1,r=n;
while(l<r){
int mid=l+r>>1;
if(b[mid]>=a[i])r=mid;//需要目标是大于a[i](第一个数)
else l=mid+1;
}
cout<<l<<' ';
l=1,r=n;
sort(a[i].begin(),a[i].end(),greater<int>());
while(l<r){
int mid=l+r+1>>1;
if(c[mid]<=a[i])l=mid;//需要目标是小于等于a[i]（最后一个数）
else r=mid-1;
}

cout<<l<<endl;

}
return 0;
}