两份代码。
第一份 TLE。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<queue>
#include<string>
#include<bitset>
#include<cctype>
#include<cstdlib>
#include<functional>
#include<istream>
#include<sstream>
#include<streambuf>
#define int long long
using namespace std;
const int N=100000,inf=0x3f3f3f3f,mod=19650827;
queue<int>q,p;
int a[N+1];
void read(int &x)
{
int d=1;
char s=getchar();
x=0;
while(s<'0'||s>'9')
if(s=='-')
{
d=-1;
s=getchar();
}
while(s>='0'&&s<='9')
{
x=x*10+s-'0';
s=getchar();
}
x*=d;
}
void print(int x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
print(x/10);
putchar(x%10+'0');
return;
}
signed main()
{
// memset(a,0,sizeof(a));
int n,x,y,ans=0;
read(n);
for(int i=1;i<=n;i++)
{
read(x);
a[x]++;
}
for(int i=1;i<=N;i++)
while(a[i]!=0)
{
q.push(i);
a[i]--;
}
for(int i=1;i<n;i++)
{
if((q.front()<p.front()&&!q.empty())||p.empty())
{
x=q.front();
q.pop();
}
else
{
x=p.front();
p.pop();
}
if((q.front()<p.front()&&!q.empty())||p.empty())
{
y=q.front();
q.pop();
}
else
{
y=p.front();
p.pop();
}
ans+=x+y;
p.push(x+y);
}
print(ans);
return 0;
}
第二份用了优先队列,RE + TLE,样例无输出。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<queue>
#include<string>
#include<bitset>
#include<cctype>
#include<cstdlib>
#include<functional>
#include<istream>
#include<sstream>
#include<streambuf>
#define ll long long
using namespace std;
const int N=100,inf=0x3f3f3f3f,mod=19650827;
priority_queue<ll,vector<ll>,greater<ll> >q,p;
int main()
{
int n,x;
ll ans=0,a,b;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
q.push(x);
}
for(int i=1;i<n;i++)
{
if((q.top()<p.top()&&!q.empty())||p.empty())
{
a=q.top();
q.pop();
}
else
{
a=p.top();
p.pop();
}
if((q.top()<p.top()&&!q.empty())||p.empty())
{
b=q.top();
q.pop();
}
else
{
b=p.top();
p.pop();
}
ans+=a+b;
p.push(a+b);
}
printf("%lld",ans);
return 0;
}
QAQ