Emotional Code|

Nolca

园龄:6年9个月粉丝:12关注:9

数学&算法 随想/哲思/思考

如何区别算法岗与前端岗:

遇到算法题 https://www.acwing.com/problem/content/242/
思维扁平,逻辑简单,甚至连题都没读懂be like(目前水平):

#include"ac.h"
#include<bits/stdc++.h>
using namespace std;
const int N=50000;
int p[N];
void init(int n){
for (int i=1; i<=n; i++) p[i]=i;
}
int findRoot(int x){
if (p[x]==x) return x;
else return findRoot(p[x]);
}
int main(){
ri;
int n,k,faker=0,d,x,y;
cin>>n>>k;
init(n);
while (k--){
cin>>d>>x>>y;
if (x>n||y>n) {faker++; continue;}
if (d==1){
//同类
if ((p[x]==y || p[y]==x)&& x!=y) {faker++; continue;}
else p[y]=p[x];
db(x);
} else {
//吃
if (x==y || p[x]==y) {faker++; continue;}
db(y);
}
}
cout<<faker;
}

自己读懂题后,跟着大佬一步一步写:

//#include"ac.h"
#include<bits/stdc++.h>
using namespace std;
const int N=50000;
int p[N],d[N];
void init(int n){
for (int i=1; i<=n; i++) p[i]=i;
}
int find(int x){
if (p[x]!=x){
int t=find(p[x]);
// db_(x);
d[x]+=d[p[x]]; //递归传递:内层给外层
p[x]=t;
//边查边压缩路径,注意递归为何需要临时变量t
// db(x); db(t); db_(p[x]);
}
return p[x];
//return t;也可以,但返回x不行,递归导致x是上次内层的数
}
int main(){
// ri;
int n,k,faker=0,D,x,y;
cin>>n>>k;
init(n);
while (k--){
cin>>D>>x>>y;
if (x>n||y>n) faker++;
else {
int px=find(x),py=find(y);
if (D==1){
//同类
if (px==py && (d[x]-d[y])%3) faker++;
//px==py保证在同一棵树上,在同一棵树上才可以推算级别关系
else if (px!=py){
p[py]=px;
d[py]=d[x]-d[y];
}
} else {
//吃
if (px==py && (d[x]-d[y]-1)%3) faker++;
//%3仅用作判断,不影响并查集树图结构,只是说不满足条件就不嫁接了
else if (px!=py){
p[py]=px;
d[py]=d[x]-d[y]-1;
//如果是y嫁接给x,则d[py]通常都是负数
}
}
}
}
cout<<faker;
}
//仍待思考:find()有路径压缩,那么p[]的树状结构只有2层?

学算法是为了学思路、学逻辑、学性情

本文作者:Nolca

本文链接:https://www.cnblogs.com/nolca/p/16710500.html

版权声明:本作品采用 收益分享revenue sharing 许可协议进行许可。

posted @   Nolca  阅读(32)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 ⏩intro 山姆精
  2. 2 🎸吉他 马叉
  3. 3 ☁升调 山姆精
  4. 4 🐦Flutter Virtual Riot/Madi
  5. 5 🎶纯律 山姆精
  6. 6 👻yeah~Color Bass! VR
⏩intro - 山姆精
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.