python的,最后三个TLE了,有没有大佬帮忙看看谢谢

P1803 凌乱的yyy / 线段覆盖

@[lzysxfcs](/user/1231862) 新加了的三个数据好像不太容易用 Python 过,看了看记录,加了三个点之后就没有正常过的,都是套了数据。 另外插入代码可以见编辑回复上栏的 `</>` 按键,选择 Python 代码插入,直接在编辑栏写的是 Markdown 语法,不是记事本谢谢。
by Terrible @ 2024-04-09 12:19:13


@[Terrible](/user/195942) 哦哦哦,原来如此,怪不得每次我的代码都这么乱,谢谢谢谢,的确,最后三个对python太不友好了,但是没办法只会一点python哈哈哈
by lzysxfcs @ 2024-04-09 12:24:02


```python n = int(input()) match = [] for i in range(n): start,end = map(int,input().split()) match.append((start,end)) #(开始,结束) match.sort(key =lambda x:(x[1],-x[0])) #结束时间由小到大,开始时间由大到小 sum = 1 #第一个比赛一定参加 end = match[0][1] for i in range(1,n): #从第二个比赛开始判断 if match[i][0] >=end: #下场比赛开始时间大于等于当前结束时间 sum +=1 #参加 end = match[i][1] #结束时间更新为下场比赛结束时间 print(sum) ``` 这是完整代码,有大佬可以处理最后三点的麻烦帮忙看看,谢谢了
by lzysxfcs @ 2024-04-09 12:53:34


```python import sys n = int(sys.stdin.readline().strip()) matches = [] for _ in range(n): start, end = map(int, sys.stdin.readline().strip().split()) matches.append((end, start)) matches.sort() count = 0 current_end = -1 for end, start in matches: if start >= current_end: current_end = end count += 1 print(count) ``` 我觉得最多还能用个快读,时间过了,但是空间占用太大了,因为在相同的结束时间里我们应该只用到了开始时间最大的,剩下的应该去掉,但是如果在建立列表过程中查找是否重复的话代价太大了,时间没法过,于是我尝试了一下用字典来做,但是字典排序很麻烦,因为字典无序,所以我们需要把它转化成有序字典或者列表,这样一来时间空间都不够用了,我建议可以用动态规划,这是一个典型的LIS,就是最长上升子序列问题,等我好消息
by dracuxi @ 2024-04-09 21:29:27


```python import sys n = int(sys.stdin.readline().strip()) matches_dict = {} for _ in range(n): start, end = map(int, sys.stdin.readline().strip().split()) if end in matches_dict.keys(): matches_dict[end] = max(start, matches_dict[end]) else: matches_dict[end] = start matches_dict = sorted(matches_dict.items()) count = 0 current_end = -1 for i in range(len(matches_dict)): (end, start) = matches_dict[i] if start >= current_end: current_end = end count += 1 print(count) ``` 这个是我用字典做的,第8组空间超了,9和10 时间超了
by dracuxi @ 2024-04-09 21:31:22


@[dracuxi](/user/945662) 好的感谢,等我明天再研究研究代码,今天太累了,写的头都大了,一点不会
by lzysxfcs @ 2024-04-09 23:01:42


#试试 ``` #include <bits/stdc++.h> using namespace std; int n ,ans=0; struct node { int x,y; } q[1000005]; bool cmp(node t1,node t2) { return (t1.y<t2.y); } int main() { scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d%d",&q[i].x,&q[i].y); } sort(q+1,q+n+1,cmp); int end=0; for(int i=1; i<=n; i++) { if(end<=q[i].x)end=q[i].y,ans++; } printf("%d",ans); return 0; } ```
by ZY10115 @ 2024-04-13 20:40:11


@[ZY10115](/user/947026) 感谢分享,但我是用的python,C语言看不太懂
by lzysxfcs @ 2024-04-14 18:06:38


|