当前位置:网站首页>E - 食物链
E - 食物链
2022-07-06 06:08:00 【RCyyds】
传送门:食物链
题意:题意简单,直接看题目即可。
思路:这是个经典的带权并查集题目了。
根据惯例,我们需要两个数组,一个是父亲节点数组p,另一个为记录x到p[x]的权值的d[x]数组,在这里规定x吃p[x]。
这道题的难点在于吃与被吃的数组d之间的关系。
1.假如x与y是同类且用共同的祖宗节点,那么就判定d[x]-d[y])%3是否等于0,等于0就代表与所说的话一致,反之不一致,ans++;
2.假如x与y是同类且没用共同的祖宗节点,就让px的父亲节点为py,算出d[px],d[px]=d[y]-d[x];
3.假如x吃y且用共同的祖宗节点,那么就判定d[x]-d[y]-1)%3是否等于0,等于0就代表与所说的话一致,反之不一致,ans++;
4.假如x吃y且没用共同的祖宗节点,就让px的父亲节点为py,算出d[px],d[px]=d[y]-d[x]+1;
5.假如x,y大于n,ans++;
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=5e4+5;
int p[N],d[N];
int find(int x)
{
if(x!=p[x])
{
int t=find(p[x]);
d[x]+=d[p[x]];
p[x]=t;
}
return p[x];
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
for (int i = 1; i <= n; i ++ ) p[i] = i;
int ans=0;
while(k--)
{
int t,x,y;
scanf("%d%d%d",&t,&x,&y);
int px=find(x),py=find(y);
if (x > n || y > n) ans ++ ;
else
{
if(t==1)
{
if(px==py&&(d[x]-d[y])%3) ans++;
else if(px!=py)
{
p[px]=py;
d[px]=d[y]-d[x];
}
}
else{
if(px==py&&(d[x]-d[y]-1)%3) ans++;
else if(px!=py)
{
p[px]=py;
d[px]=d[y]-d[x]+1;
}
}
}
}
printf("%d",ans);
return 0;
}
边栏推荐
- [C language] string left rotation
- [postman] the monitors monitoring API can run periodically
- The latest 2022 review of "graph classification research"
- Title 1093: character reverse order
- Gtest之TEST宏的用法
- Testing and debugging of multithreaded applications
- 《卓有成效的管理者》读书笔记
- Application du Groupe Li dans gtsam
- Eigen sparse matrix operation
- Overview of three core areas of Mathematics: geometry
猜你喜欢
P问题、NP问题、NPC问题、NP-hard问题详解
假设检验学习笔记
【Tera Term】黑猫带你学TTL脚本——嵌入式开发中串口自动化神技能
[API interface tool] Introduction to postman interface
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
功能安全之故障(fault),错误(error),失效(failure)
C language bubble sort
Huawei BFD configuration specification
Sqlmap tutorial (III) practical skills II
Buuctf-[gxyctf2019] no dolls (xiaoyute detailed explanation)
随机推荐
How to recover Huawei router's forgotten password
测试周期被压缩?教你9个方法去应对
Function of activation function
J'ai un chaton.
数学三大核心领域概述:几何
假设检验学习笔记
Cognitive introspection
CoordinatorLayout+NestedScrollView+RecyclerView 上拉底部显示不全
[paper reading] nflowjs: synthetic negative data intensive anomaly detection based on robust learning
LeetCode 729. 我的日程安排表 I
The latest 2022 review of "graph classification research"
MPLS test report
误差的基本知识
Introduction to promql of # yyds dry goods inventory # Prometheus
Dynamic programming -- knapsack problem
Linux regularly backs up MySQL database
Significance of unit testing
进程和线程的理解
Novice entry SCM must understand those things
LeetCode 732. 我的日程安排表 III