Codeforces - 1097B Petr and a Combination Lock
原题地址
Description
Petr has just bought a new car. He’s just arrived at the most known Petersburg’s petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360360 degrees and a pointer which initially points at zero:
Petr called his car dealer, who instructed him to rotate the lock’s wheel exactly nn times. The ii-th rotation should be aiai degrees, either clockwise or counterclockwise, and after all n rotations the pointer should again point at zero.
This confused Petr a little bit as he isn’t sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all nn rotations the pointer will point at zero again.
Input
The first line contains one integer nn (1 ≤ n ≤ 15) — the number of rotations.
Each of the following nn lines contains one integer ai (1 ≤ ai ≤ 180) — the angle of the i-th rotation in degrees.
Output
If it is possible to do all the rotations so that the pointer will point at zero after all of them are performed, print a single word “YES”. Otherwise, print “NO”. Petr will probably buy a new car in this case.
You can print each letter in any case (upper or lower).
Examples
Input | Output |
---|---|
3 10 20 30 | YES |
3 10 10 10 | NO |
3 120 120 120 | YES |
Note
In the first example, we can achieve our goal by applying the first and the second rotation clockwise, and performing the third rotation counterclockwise.
In the second example, it’s impossible to perform the rotations in order to make the pointer point at zero in the end.
In the third example, Petr can do all three rotations clockwise. In this case, the whole wheel will be rotated by 360 degrees clockwise and the pointer will point at zero again.
思路:
每次旋转有两种状态,即顺时针和逆时针旋转,相应对应正负两个状态。
观察得出旋转次数最多也就15次,即2^15次,不会TLE,于是就想到遍历一遍每个旋转是顺时针还是逆时针,是正还是负。
以上。
AC代码:
#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
#include<sstream>
#include<string.h>
#include<cmath>
using namespace std;
int main(){
int n;
int t[20],p[20]; //t是数字,p是符号
cin >> n;
for(int h = 0;h < n;h ++){
scanf("%d",&t[h]);
}
int i;
fill(p,p + n,1);
for(i = 0;i < (1 << n);i ++){ //(1 << n) 即 2^n,1的二进制左移n位
int k = i,w = 0;
int sum = 0;
while(k != 0){
if(k & 1)p[w ++] = 1; //按位与计算,就是判断k是否为奇数
else p[w ++] = -1;
k >>= 1;
}
for(int j = 0;j < n;j ++){
sum += p[j] * t[j];
}
if(sum % 360 == 0)break;
}
if(i < (1 << n))printf("YES");
else printf("NO");
}