A - Garland
思路:只有四个灯 其实就只有四种情况:全都不同时4次,其中俩个相同时4次,其中三个相同时6次,四个都相同时无法完成
#include <iostream>
#include <stdio.h>
#include <unordered_map>
using namespace std ;
const int N = 1e5+10;
int n , m ;
void check(string s)
{
int res = 0 ;
int cnt[10] = {0 };
for(int i = 0 ; i < 4 ; i++ ){
cnt[ s[i] -'0' ] ++ ;
res = max(cnt[ s[i] -'0' ] , res );
}
if( res == 1) puts("4");
else if(res == 2) puts("4");
else if( res == 3) puts("6");
else puts("-1");
}
int main()
{
int T ;
scanf("%d", &T);
while ( T -- ){
char s[5] ;
scanf("%s", s);
check(s) ;
}
return 0;
}
B - Points on Plane
提示:使用二分法、贪心、数学方法(等差数列前n项和)
思路:二维平面其实是二维直角坐标系,既然两两之间要隔大于1的欧几里得距离,且要使得坐标尽量小,所以各个点的选择要尽量靠近中心(0,0),我们可以将所有需要用到的点平均分散到四个象限中,那么只需要计算其中一个象限就好了,我们计算第一象限。各个点在第一象限中按照斜45度角的直线放置
其中又分为两种情况,绿色的数字为这条线能放置的点数,
红色的线为情况1:(原点算一个)1、2、4、6、8....an
黑色的线为情况2:1、3、5....an
看出来都是公差为2的等差数列,情况1 需要将原点另外计算
计算等差数列前n项和的公式为 (a1 + an) n / 2 ,其中,为方便计算:
情况1:将a1设为2,an从4开始
情况2:将a1设为1,an从3开始
这样的话需要将前9个答案枚举出来
n 为数组的元素个数,可以用an/2 , 情况2时为an/2 + 1,例如:数列1、3、5中,5 / 2=2 ,n = 2+1 = 3。数列2、4、6中,n = 6 / 2 = 3
根据题目给出的样例中,975461057789971042为一个19位的十进制数,其答案为一个9位的十进制数,我们将二分的范围定到了4~1e9 和 3~1e9
每次都要计算两种方法的结果,最终取较小的一个
#include <iostream>
#include <algorithm>
using namespace std ;
typedef long long LL ;
const int N = 1e5+10;
int n , m ;
LL num ;
LL ans1 , ans2 ;
LL t1 , t2 ;
bool check1(LL x )//x从4开始
{
//调整一下计算的顺序有助于避免直接相乘后超出能够表示的数字
LL sum = (2 + x) / 2 * (x / 2 ) ;
if(sum >= t1){
return true ;
}
return false ;
}
bool check2(LL x ) //x从3开始
{
LL sum = (1 + x) / 2 * (x / 2 + 1);
if( sum >= t2){
return true ;
}
return false;
}
int main()
{
int T ;
scanf("%d", &T);
int a[10] = {-1,0,1,1,1,2,2,2,2,2};
while ( T -- ){
t1 = 0 , t2 = 0 , ans1 = 0 , ans2 = 0 ;
cin >> num ;
if(num <= 9 ) {
printf("%d\n",a[num]);continue;
}
t1 = (num - 1) / 4 + ( (num - 1) % 4 == 0 ? 0 : 1);
t2 = num / 4 + (num % 4 == 0 ? 0 : 1);
LL l = 4 , r = 1e9;
while ( l < r){
LL mid = l + r >> 1;
if( check1(mid)) r = mid ;
else l = mid + 1;
}
ans1 = r ;//an
l = 3 , r = 1e9;
while ( l < r){
LL mid = l + r >> 1;
if(check2(mid)) r = mid ;
else l = mid + 1;
}
ans2 = r ;
cout <<min(ans1 , ans2) <<" " <<endl;
}
return 0;
}