[笔试训练](十五)

目录

043:平方数 

044:分组

045:拓扑排序


043:平方数 

平方数 (nowcoder.com)

题目:

题解:

简单题,开根号之后判断左右两个数哪个离得近。

#include <iostream>
#include <cmath>
using namespace std;
typedef long long LL;
int main()
{
    LL x;
    cin >> x;
    LL a = sqrt(x);//开平方根
    LL x1 = a * a, x2 = (a + 1) * (a + 1);
    if(x - x1 < x2 - x) cout << x1 << endl;
    else cout << x2 << endl;
    return 0;
}

044:分组

分组 (nowcoder.com)

题解:

枚举所有可能的小组人数为最多小组人数,当刚好可以满足条件时,为真的最大小组人数。

优化:二分

#include<iostream>
#include<algorithm>
#include<unordered_map>
using namespace std;

int n,m;
unordered_map<int,int> cnt;

bool check(int i)
{
    int g=0;
    for(auto& [a,b] : cnt)
    {
        g+=b/i+(b%i==0?0:1);
    }
    return g<=m;
}

int main()
{
    cin>>n>>m;
    int hmax=0;//统计声部最多人数
    for(int i=0;i<n;i++)
    {
        int x;
        cin>>x;
        hmax=max(++cnt[x],hmax);
    }
    
    int kinds=cnt.size();
    if(kinds>m)
    {
        cout<<-1<<endl;
    }
    else
    {
//         //暴力枚举
//         for(int i=1;i<=hmax;i++)
//         {
//             if(check(i))
//             {
//                 cout<<i<<endl;
//                 break;
//             }
//         }
        
        // ⼆分解法
    int l = 1, r = hmax;
    while(l < r)
    {
        int mid = (l + r) / 2;
        if(check(mid)) r = mid;
        else l = mid + 1;
    }
        cout << l << endl;

    }
     
    return 0;
}

045:拓扑排序

【模板】拓扑排序_牛客题霸_牛客网 (nowcoder.com)

题解: 

题解:

拓扑排序模版题:

        1.建图

        2.度为0的入队列

        3.层序遍历

#include <iostream>
#include<vector>
#include<queue>

using namespace std;
const int N=2e5+10;
int n,m;
vector<vector<int>> edges(N);//建图edges[i]表示与i链接的边的信息
int in[N];
queue<int> q;//入度
vector<int> ret;//统计结果

int main() 
{
    cin>>n>>m;
    while(m--)
    {
        int a,b;
        cin>>a>>b;
        edges[a].push_back(b);//存储边的信息
        in[b]++;//存储入度
    }

    //度为0的入队列
    for(int i=1;i<=n;i++)
    {
        if(in[i]==0)
        {
            q.push(i);
        }
    }

    while(q.size())
    {
        int a=q.front();
        q.pop();
        ret.push_back(a);
        for(auto b:edges[a])
        {
            if(--in[b]==0)
            {
                q.push(b);
            }
        }
    }

    //判断
    if(ret.size()==n)
    {
        for(int i=0;i<n-1;i++)
        {
            cout<<ret[i]<<" ";
        }
        cout<<ret[n-1]<<endl;//考虑最后一个空格
    }
    else
    {
        cout<<-1<<endl;
    }


    return 0;
}
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲敲er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值