解题思路:
并查集吧
为毛超时啊??
最强召唤魔法,地表最强召唤兽~@地表最强召唤兽
注意事项:
参考代码:
#include <iostream> #include <stdio.h> #include <vector> #include <map> using namespace std; map<int, int> dollSet; int Q(int x) { int ans = 0; while (dollSet[x] != x && dollSet[x] != 0) { x = dollSet[x]; ans += 1; } return ans; } int P(int x, int n) { int count = 0; int preX = x; while (dollSet[x] != x && dollSet[x] != 0) { //找前驱是x的结点的值,前驱->前驱的前驱 for (map<int, int>::iterator it = dollSet.begin(); it != dollSet.end(); it++) if (it->second == x) it->second = dollSet[x]; preX = x; x = dollSet[x]; count += 1; } //解开根结点,构造一个虚拟的“根结点” for (map<int, int>::iterator it = dollSet.begin(); it != dollSet.end(); it++) if (it->second == n) it->second = 0; return count; } int main(void) { int n,m; cin >> n >> m; for (int i = 1; i <= n - 1; i++) { int a,b; cin >> a >> b; dollSet[b] = a; } dollSet[n] = n; for (int i = 0; i < m; i++) { char ch; int x; cin >> ch >> x; switch (ch) { case 'Q': cout << Q(x) << "\n"; break; case 'P': cout << P(x, n) << "\n"; break; } } return 0; }
0.0分
5 人评分
dollSet[n] = n;感觉这句没有什么依据,因为节点的标号是从1-n 如果是设置虚拟节点的话,应该是n+1吧
沐里纷纷 2018-12-15 22:16:51 |
这句应该就是并查集的终止条件吧,就是根结点指向自己,把这个作为找前驱节点的终止条件。是有点问题,后面如果有P操作,可能会破坏根结点的“根”的属性,我就增加一个虚拟的根结点,原根结点作为虚拟根节点的子结点
我也没搞懂这题,想了好久,决定放弃了他,太惨了,我写的方法也是超时的。
沐里纷纷 2018-12-15 22:18:00 |
感觉可能是oj答案的问题,能把管理员召唤出来吗
2006年春浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:805 |
【矩阵】 (C++代码)浏览:936 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:262 |
1009题解浏览:736 |
C语言程序设计教程(第三版)课后习题5.8 (C语言代码)浏览:1152 |
循环入门练习5 (C语言代码)浏览:829 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:342 |
震宇大神的杀毒软件 (C语言代码)浏览:1079 |
P1002 (C++代码)浏览:706 |
用getchar()函数接收字符,正序输入为什么会倒序输出浏览:741 |