Build Tree
http://acm.hdu.edu.cn/showproblem.php?pid=6533
题意:一颗m层的满n叉树,从k数组中不重复的选择一些数作为树的边,使得所有节点到根节点的距离之和最小
题解:对于一颗m层的满n叉树而言,某条边重复计算的次数是该边连接的子树的结点的数量,因为是满n叉树,所以这个结点数量是可以O(1)求出的,求min时,只要贪心选择小的权值为边赋值,O(E)复杂度内即可算出。而排序复杂度是O(NlogN),所以总复杂度是O(NlogN+E)。
C++版本一
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
#define endl "\n"
using namespace std;
typedef long long ll;
typedef __int128 lll;
const int N=200000+10;
const int M=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
ll t,n,m,k,p,l,r,u,v;
ll ans,cnt,flag,temp,sum;
ll a[N];
char str;
struct node{};
ll POW(ll a,ll b,ll c){
ll res=1;
ll base=a%c;
while(b){
if(b&1)res=(res*base)%c;
base=(base*base)%c;
b>>=1;
}
return res;
}
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
//scanf("%d",&t);
//while(t--){
while(~scanf("%lld%lld%lld%lld",&k,&m,&n,&p)){
for(int i=1;i<=k;i++)scanf("%lld",&a[i]);
if(m==0||n==0){
cout<<0<<endl;
continue;
}
sort(a+1,a+k+1);
int pos=n;
int fac=m-1;
ans=0;
for(int i=1;i<=k;i++){
if(!fac)break;
ans=(ans+((a[i]%p)*(n==1?fac:(POW(n,fac,p)-1)/(n-1)))%p)%p;
//cout<<(ll)(POW(n,fac,p)-1)/(n-1)<<endl;
if(i==pos){
//cout<<pos<<endl;
fac--;
pos=pos+POW(n,m-fac,p);
}
}
cout<<ans<<endl;
}
//}
#ifdef DEBUG
printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
//cout << "Hello world!" << endl;
return 0;
}