分类:贪心
题目链接:LA4850-Installations
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=500+5;
struct node
{
int s,d;
}a[maxn];
bool cp(const node &x,const node &b)
{
return x.d<b.d;
}
int pos=0;
int cal(int i)
{
int time=0;
int m1=0;
int m2=0;
for(int j=0;j<=pos;j++)
{
if(i==j)
{
continue;
}
time+=a[j].s;
int f=max(0,time-a[j].d);
if(m1<f)
{
m2=m1;
m1=f;
}
else if(m2<f)
{
m2=f;
}
}
time+=a[i].s;
int f=max(time-a[i].d,0);
if(m1<f)
{
m2=m1;
m1=f;
}
else if(m2<f)
{
m2=f;
}
return m1+m2;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d %d",&a[i].s,&a[i].d);
}
int ans,time,m1,m2;
ans=pos=m1=m2=time=0;
sort(a,a+n,cp);
for(int i=0;i<n;i++)
{
time+=a[i].s;
int f=max(time-a[i].d,0);
if(m1<f)
{
m2=m1;
m1=f;
pos=i;
}
else if(m2<f)
{
m2=f;
pos=i;
}
}
ans=m1+m2;
for(int i=0;i<pos;i++)
{
ans=min(cal(i),ans);
}
printf("%d\n",ans);
}
return 0;
}