C. p-binary

 C. p-binaryios

思路:枚舉加了i次,而後把n把多加的i*p減回來得m,如今看m的二進制數,看其中爲1 的有多少個(這個爲我寫的ss函數),以後看i的個數和ss返回值,只要返回值i小於等於1的個數,就能夠是答案了函數

  if (ss <= i&&m>=i)   高位次的2可由低位次的2補救,spa

這個判斷緣由是,假設拿1算的話,若是m<i*1()就沒有更小的值符合條件code

 

 

1 #include <iostream>
 2 #include<algorithm>
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 #include<string.h>
 6 #include<map>
 7 #include<queue>
 8 #include<vector>
 9 #include<string>
10 using namespace std; 11 #define inf 0x3f3f3f 12 int ss(int a) 13 { 14 int sum = 0; 15 while (a) 16  { 17 if (a & 1) 18  { 19 sum++; 20  } 21 a >>= 1; 22  } 23 return sum; 24 } 25 int main() 26 { 27 int n, p, m; 28 cin >> n >> p; 29 int flag = 0; 30 for (int i = 1; i*p<=n; i++) 31  { 32 flag++;//若p爲負數,則一直循環,因此加跳出條件,1000以前有答案的話確定有答案了 33 if (flag > 1000) 34 break; 35 m = n - p * i; 36 int s = ss(m); 37 if (s <= i&&m>=i) 38  { 39 cout << i << endl; 40 return 0; 41  } 42 43  } 44 cout << -1 << endl; 45 return 0; 46 }
相關文章
相關標籤/搜索