贪心法(服务器最少跳转次数)
程序员文章站
2022-03-15 19:21:57
...
找约数的个数O(n^0.5)
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int exe(int n) {
int ans = 0;
int bound = sqrt(n) + 1;
for (int i = 1; i <= bound; i++) {
if (n%i == 0) {
++ans;
if (n / i > bound) ++ans;//一对儿,在另一半也有一个
}
}
return ans;
}
int main()
{
//data
int n = 0;
int x = 0;
//input
cin >> n;
for (size_t i = 0; i <n; i++)
{
cin >> x;
cout<< exe(x)<<endl;
}
//output
//system("pause");
return 0;
}
代理服务器最少跳转几次
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
//data
int n,m;
char proxy[1000][16];
char server[2000][16];
//input
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", proxy[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%s", server[i]);
}
//贪心法
int index = 0, count = 0, flag = 1;
while (index < m) {
int max = 0;
for (int i = 0; i < n; i++) {
//遍历每一个代理服务器,看其从当前位置最多可以访问到多少服务器max
int j = index;
while (strcmp(proxy[i], server[j]) && j < m)
j++;
if (j - index > max) max = j - index;
}
if (max == 0) {
flag = 0;
break;
}
count++;
index += max;
}
//output
if (flag)
printf("%d\n", count - 1); //因为第一次不算转换
else
printf("-1\n");
return 0;
}
质数的分解:120=2×2×2×3×5
#include <iostream>
#include <cmath>
using namespace std;
int main() {
//这题的关键:
//1、是sqrt,可以极大减少复杂度,若是到方根N仍大于1,则必还有且只还有1个质因数
//2、每次瞬间整除都可帮助减少遍历范围
long M = 100;
while (cin >> M)
{
long count = 0;
for (long j = 2; j <= sqrt(M); j++)
{
while (M%j == 0)
{
M = M / j;
count++;
}
if (M <= 1)break;
}
if (M > 1)count++;
cout << count << endl;
}
return 0;
}
上一篇: 肋排和小排区别
下一篇: mysql 事务解析
推荐阅读