USCAO-Section 1.3 Combination Lock

原题:
Farmer John’s cows keep escaping from his farm and causing mischief. To try and prevent them from leaving, he purchases a fancy combination lock to keep his cows from opening the pasture gate.

Knowing that his cows are quite clever, Farmer John wants to make sure they cannot easily open the lock by simply trying many different combinations. The lock has three dials, each numbered 1..N (1 <= N <= 100), where 1 and N are adjacent since the dials are circular. There are two combinations that open the lock, one set by Farmer John, and also a “master” combination set by the lock maker.

The lock has a small tolerance for error, however, so it will open even if the numbers on the dials are each within at most 2 positions of a valid combination.

For example, if Farmer John’s combination is (1,2,3) and the master combination is (4,5,6), the lock will open if its dials are set to (1,3,5) (since this is close enough to Farmer John’s combination) or to (2,4,8) (since this is close enough to the master combination). Note that (1,5,6) would not open the lock, since it is not close enough to any one single combination.

Given Farmer John’s combination and the master combination, please determine the number of distinct settings for the dials that will open the lock. Order matters, so the setting (1,2,3) is distinct from (3,2,1).

题意和题解:
密码锁:(a,b,c)1<=a,b,c<=N;
给定两个可以打开密码锁的密码,如:(1,2,3) (4,5,6);由于密码锁的问题,只要输入的密码和这两个密码的每位相差距离不超过2就可以打开密码锁,由于密码锁是环形的,所以1和N的相差距离是1,依次规律求出输入N和两个开锁密码后的可以打开密码锁的所有密码是数量。

解题思路:写一个判断函数判断两个数相差的距离是否满足要求;
bool isOK(int a,int b){
return abs(a-b)<=2||abs(a-b)>=n-2;
}
然后枚举加判断计数统计就行。

代码:

/*
ID:newyear111
PROG: combo
LANG: C++
*/

#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=105;

int a[3],b[3];
int n;
int isOK(int a,int b){
    return abs(a-b)<=2||abs(a-b)>=n-2;
}
int main()
{
    ifstream fin("combo.in");
    ofstream fout("combo.out");

    fin>>n;
    fin>>a[0]>>a[1]>>a[2];
    fin>>b[0]>>b[1]>>b[2];
    int ans=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            for(int k=1;k<=n;k++){
                if((isOK(i,a[0])&&isOK(j,a[1])&&isOK(k,a[2]))||(isOK(i,b[0])&&isOK(j,b[1])&&isOK(k,b[2])))
                {
                    ans++;
                }
            }
        }
    }   
    fout<<ans<<endl;
    fin.close();
    fout.close();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值