链式投票|流向贪心

lc2147

抽离出座位位置,座位数非偶或为0则无方案,否则每两组座位间的间隔数相乘,取模得方案数。

class Solution {

typedef long long ll;

public:

int numberOfWays(string corridor)

{

int n=corridor.size();

vector<int> s;

for(int i=0;i<n;i++)

{

char c=corridori;

if(c=='S')

s.push_back(i);

}

int m=s.size();

if(m%2 || m==0) return 0;

ll ret=1;

const int mod=1e9+7;

for(int i=2;i<m;i+=2)

{

int d=si-si-1;

ret=(ret*(ll)d)%mod;

}

return (int)(ret%mod);

}

};

lc2022

++if(len!=m*n)++

++return {};//check++

class Solution {

public:

vector<vector<int>> construct2DArray(vector<int>& original, int m, int n)

{

vector<vector<int>> ret(m,vector<int>(n,0));

int len=original.size();

++if(len!=m*n)++

++return {};//check++

for(int i=0;i<len;i++)

{

reti/ni%n=originali;

}

return ret;

}

};

lc797

先凑总和非负,找唯一负数位置

从近到远取两边正数补负数,累计移动步数得最小操作数

class Solution {

public:

long long minMoves(vector<int>& balance) {

long long total = 0;

int neg_idx = -1;

for (int i = 0; i < balance.size(); i++) {

int x = balancei;

total += x;

if (x < 0) {

neg_idx = i;

}

}

if (total < 0) { // 总和必须非负

return -1;

}

if (neg_idx < 0) { // 没有负数,无需操作

return 0;

}

int n = balance.size();

++int need = -balanceneg_idx;++

long long ans = 0;

++for (int dis = 1; ; dis++) {++

// 把与 neg_idx 相距 dis 的数移到 neg_idx

++int s = balance(neg_idx - dis + n) % n + balance(neg_idx + dis) % n;++

if (s >= need) {

ans += 1LL * need * dis;

// need 个 1 移动 dis 次

return ans;

}

++ans += 1LL * s * dis; // s 个 1 移动 dis 次
need -= s;
++

}

}

};

lc277

1.找候选人

2.check候选人(3种situation)

/* The knows API is defined for you.

bool knows(int a, int b); */

class Solution

{

public:

int findCelebrity(int n)

{

int candidate = 0; //候选人

for (int x = 1; x < n; x ++)

{

if ( knows(candidate, x) == true ) //若候选人认识别人,就不可能是名人。名人不认识其他人

{

candidate = x; //所有人,一定认识名人

//////小于x的那些,要么是因为 (1)被人不知,if被人知,就抢到了candidate了

//////(2) 要么是因为认识了别人,就放弃了candidate

}

}

for (int x = 0 ; x < n; x ++)

{

if (candidate == x) //名人不认识其他人,但是认识自己

continue;

if ( knows(candidate, x) == true)

return -1; //名人不应该认识 anyone

if (knows(x, candidate) == false)

return -1; //anyone 认识名人

}

return candidate;

}

};

相关推荐
不会就选b13 分钟前
算法日常・每日刷题--<归并排序>1
数据结构·算法
啦啦啦啦啦zzzz39 分钟前
算法:回溯算法
c++·算法·leetcode
IT探索1 小时前
Linux 查找文件指令总结
linux·算法
Lumos1862 小时前
51单片机从零到实战(完结)——后续学习路线建议
算法
稚南城才子,乌衣巷风流2 小时前
DFS序详解:原理、应用与实现
算法·深度优先·图论
稚南城才子,乌衣巷风流2 小时前
动态树(Dynamic Tree)数据结构详解
数据结构·算法
变量未定义~3 小时前
最小生成树1(Prim模板)、最小生成树2(kruskal模板)、最近公共祖先(模板)
算法
这就是佬们吗3 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm
LONGZETECH3 小时前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车