将每一个数写为2进制。计算公共前缀
答案必为 [最长公共前缀(LCS)]+00...00
证:
若LCS后有1
则每一个数都要在对应位置有1,
故LCS可增长。矛盾
#include#include #include #include #include #include #include #include #include using namespace std;#define For(i,n) for(int i=1;i<=n;i++)#define Fork(i,k,n) for(int i=k;i<=n;i++)#define Rep(i,n) for(int i=0;i =0;i--)#define Forp(x) for(int p=pre[x];p;p=next[p])#define Forpiter(x) for(int &p=iter[x];p;p=next[p]) #define Lson (x<<1)#define Rson ((x<<1)+1)#define MEM(a) memset(a,0,sizeof(a));#define MEMI(a) memset(a,127,sizeof(a));#define MEMi(a) memset(a,128,sizeof(a));#define INF (2139062143)#define F (100000007)#define MAXN (100000+10)typedef long long ll;ll mul(ll a,ll b){return (a*b)%F;}ll add(ll a,ll b){return (a+b)%F;}ll sub(ll a,ll b){return (a-b+(a-b)/F*F+F)%F;}void upd(ll &a,ll b){a=(a%F+b%F)%F;}int n,a[MAXN],a2[MAXN],h[MAXN]={0},q[MAXN]={0};int main(){ freopen("C.in","r",stdin);// freopen(".out","w",stdout); cin>>n; For(i,n) scanf("%d",&a[i]); sort(a+1,a+1+n); memcpy(a2,a,sizeof(a)); int p=a[1]; For(i,n) { while (p^a[i]) { if (p >=1; else p>>=1; } } memcpy(a,a2,sizeof(a)); For(i,n) { while (a[i]^p) { h[i]--; if (a[i]&1) q[i]=h[i]; a[i]>>=1; } } ll ans=INF; Rep(t,100) { ll p=0; For(i,n) { if (q[i]==0||h[i]+t<=q[i]) p+=abs(h[i]+t); else p+=abs(q[i])+abs(q[i]-(h[i]+t)); } ans=min(ans,p); } cout< <