比赛 中秋节快乐! 评测结果 AAAAAAAAAA
题目名称 骑士 最终得分 100
用户昵称 wdsjl 运行时间 0.842 s
代码语言 C++ 内存使用 14.42 MiB
提交时间 2024-09-17 10:40:56
显示代码纯文本
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1000010;
  5.  
  6. int va[N],a,b;
  7. long long f[N][3];
  8.  
  9. struct node{
  10. int to,ne,v;
  11. }e[N*2];
  12.  
  13. int h[N],vis[N],n,s,tot,x1,x2,E;
  14.  
  15. void add(int x,int y){
  16. e[tot].to=y,e[tot].ne=h[x],h[x]=tot++;
  17. return ;
  18. }
  19.  
  20. void huan(int u,int fa){
  21. vis[u]=1;
  22. for(int i=h[u];~i;i=e[i].ne){
  23. if((i^1)==fa)continue;
  24. if(vis[e[i].to]){
  25. x1=u,x2=e[i].to;
  26. E=i;
  27. continue;
  28. }
  29. huan(e[i].to,i);
  30. }
  31. }
  32.  
  33. void dfs(int u,int fa){
  34. f[u][0]=0;
  35. f[u][1]=va[u];
  36. for(int i=h[u];~i;i=e[i].ne){
  37. if((i^1)==fa)continue;
  38. if(i==E||(i^1)==E)continue;
  39. dfs(e[i].to,i);
  40. f[u][0]+=max(f[e[i].to][0],f[e[i].to][1]);
  41. f[u][1]+=f[e[i].to][0];
  42. }
  43. return ;
  44. }
  45.  
  46. int main(){
  47. freopen("bzoj_1040.in","r",stdin);
  48. freopen("bzoj_1040.out","w",stdout);
  49. memset(h,-1,sizeof(h));
  50. scanf("%d",&n);
  51. for(int i=1;i<=n;i++){
  52. scanf("%d%d",&a,&b),add(i,b),add(b,i),va[i]=a;
  53. }
  54. long long res=0;
  55. for(int i=1;i<=n;i++){
  56. if(vis[i])continue;
  57. huan(i,-2);
  58. dfs(x1,-1);
  59. long long cnt=f[x1][0];
  60. dfs(x2,-1);
  61. cnt=max(cnt,f[x2][0]);
  62. res+=cnt;
  63. }
  64. printf("%lld",res);
  65. return 0;
  66. }