原题:

Description
Roundgod is a famous milk tea lover at Nanjing University second to none. This year, he plans to conduct a milk tea festival. There will be n classes participating in this festival, where the ith class has ai students and will make bi cups of milk tea.

Roundgod wants more students to savor milk tea, so he stipulates that every student can taste at most one cup of milk tea. Moreover, a student can't drink a cup of milk tea made by his class. The problem is, what is the maximum number of students who can drink milk tea?

Input

The first line of input consists of a single integer T (1≤T≤25), denoting the number of test cases.

Each test case starts with a line of a single integer n (1≤n≤106), the number of classes. For the next n lines, each containing two integers a,b (0≤a,b≤109), denoting the number of students of the class and the number of cups of milk tea made by this class, respectively.

It is guaranteed that the sum of n over all test cases does not exceed 6×106.

Output

For each test case, print the answer as a single integer in one line.

    大致是说有n个班,每个班有ai个人,第i个班总共做了bi杯奶茶,这些班级随意交换奶茶,但是每个人都不能喝自己班的奶茶,每人喝一杯,问:最多有多少人可以喝到奶茶。

解题思路:

先想:第i个班可以喝多少杯奶茶?
第i个班可选择的奶茶很容易得到,就是总数(tot)-自己班做的(b[i])杯
但是每个人只喝一杯(喝多了长胖,还让别人喝不上)这个班最多只能喝a[i]杯。
若sum为奶茶数总和,那么第i个班应该能喝min(a[i],tot-b[i])杯。
如果tot-b[i]为负数,那么其他班剩下能喝的已经不足这个班的人数了,就把tot杯全部喝完。
然后用ans累加喝掉奶茶的数量。

AC代码(核心部分):

注意ans可能很大(1015),所以开long long。

因为min()和max()中只能容纳两个相同格式的变量(int,int)或(long long,long long),所以其它索性也开了long long。
long long a[6000010],b[6000010],t,n,tot,ans,x,y,z;
int main()
{
    int i;
    scanf("%d",&t);
    while(t--)
    {
        tot=ans=0;
        scanf("%d",&n);
        for(i=1;i<=n;i++)
        {
            scanf("%d%d",&a[i],&b[i]);
            tot+=b[i];
        }
        tt=tot;
        for(i=1;i<=n;i++)
        {
            x=tot-b[i],y=min(x,a[i]);
            if((tt-y)<0) y=tt;
            tt-=y,ans+=y;
        }
        printf("%lld\n",ans);
    }
}