当前位置: 代码迷 >> 综合 >> USCAO-Section 1.3 Combination Lock
  详细解决方案

USCAO-Section 1.3 Combination Lock

热度:79   发布时间:2023-09-19 12:12:08.0

原题:
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;
}
  相关解决方案