当前位置:网站首页>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;
}
边栏推荐
- 如何在业务代码中使用 ThinkPHP5.1 封装的容器内反射方法
- [leetcode] day96 - the first unique character & ransom letter & letter ectopic word
- Significance of unit testing
- 「 WEB测试工程师 」岗位一面总结
- Fault, error, failure of functional safety
- Arrays and collections
- Luogu p1460 [usaco2.1] healthy Holstein cows
- 《卓有成效的管理者》读书笔记
- Dynamic programming -- knapsack problem
- IDEA 新UI使用
猜你喜欢
随机推荐
Seven imperceptible truths in software testing
全程实现单点登录功能和请求被取消报错“cancelToken“ of undefined的解决方法
Luogu p1460 [usaco2.1] healthy Holstein cows
properties文件
【LeetCode】Day96-第一个唯一字符&赎金信&字母异位词
Bit operation rules
LAN communication process in the same network segment
The difference and usage between continue and break
公司視頻加速播放
一文揭开,测试外包公司的真 相
Caused by:org. gradle. api. internal. plugins . PluginApplicationException: Failed to apply plugin
Caused by:org.gradle.api.internal.plugins . PluginApplicationException: Failed to apply plugin
對數據安全的思考(轉載)
Reading notes of effective managers
LeetCode 732. 我的日程安排表 III
公司视频加速播放
Amazon Engineer: eight important experiences I learned in my career
Gtest之TEST宏的用法
Dynamic programming -- knapsack problem
Leaflet map



![[C language] string left rotation](/img/5f/66bcc8f992108bf3b7e455709d3174.png)


![[postman] collections - run the imported data file of the configuration](/img/85/7ac9976fb09c465c88f376b2446517.png)

