一、平方数
小问题
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
long long a;
cin >> a;
long long b = sqrt(a);
long long c = b + 1;
b = b * b;
c = c * c;
if (c - a > a-b)
cout << b;
else
cout << c;
}
二、分组
枚举+二分,先找到最大人数的组,每个组的人数不会超过他,再从0开始加到最大,找到临界点,使得组数符合要求
#include<iostream>
using namespace std;
#include<map>
int check(int i, map<int, int>& g, int x)
{
int num = 0;
for (auto j : g)
{
int k = j.second / i;
if (j.second > k * i)
num++;
num += k;
}
return num <= x;
}
int main()
{
int n, m;
map<int, int> group;
cin >> n >> m;
int mmax = 0;
int s = n;
while (n--)
{
int x;
cin >> x;
group[x]++;
if (group[x] > mmax)
mmax = group[x];
}
if (group.size() > m || s < m)
cout << "-1";
else
{
int l = 1;
int r = mmax;
while (l < r)
{
int mid = (l + r) / 2;
if (check(mid, group, m))
{
r = mid;
}
else
l = mid + 1;
}
cout << l;
}
}
三、拓扑排序
经典算法
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> top;
int topsort(vector<vector<int>>& v, vector<int>& d)
{
queue<int> q;
for (int i = 0; i < d.size(); i++)
{
if (d[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int i = q.front();
q.pop();
top.push_back(i);
for (auto j : v[i])
{
d[j]--;
if (d[j] == 0)
q.push(j);
}
}
if (top.size() == d.size())
return 1;
return 0;
}
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> v(n);
vector<int> d(n, 0);
while (m--)
{
int x, y;
cin >> x >> y;
v[x - 1].push_back(y - 1);
d[y - 1]++;
}
if (!topsort(v, d))
cout << "-1";
else
{
for (int i = 0; i < top.size(); i++)
{
if (i < top.size() - 1)
cout << top[i] + 1 << ' ';
else
cout << top[i] + 1;
}
}
}