ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1403. Courier

WA#9
Posted by KALO 3 Oct 2009 14:33
import java.io.*;

class Courier{
    static PrintWriter p=new PrintWriter(System.out);
    static int f;
    static final int k=-'0';
    int mat[][],dp[],max;
    short N,a[],l[],sa,sl;
    boolean ok;

    static int nextInt() throws IOException{
        int t=0;
        for (f=System.in.read(); f<'0' || f>'9'; f=System.in.read());
        for (;f>='0' && f<='9'; t*=10,t+=f+k,f=System.in.read());
        return t;
    }

    Courier() throws IOException{
        N=(short)nextInt();
        mat=new int[N+1][3];
        short i=1;
        for (;i<=N; mat[i][0]=nextInt(),mat[i][1]=nextInt(),mat[i][2]=i++);
        a=new short[N];
        l=new short[N];
        dp=new int[N+1];
        qsort((short) 1,N);
        for (i=1;i<=N; i++){
            if (mat[i][0]>=1){
                a[sa++]=(short) mat[i][2];
                nadji(2,i,mat[i][1]);
                sa--;
            }
        }
        for (p.println(sl),i=0; i<sl; p.print(l[i++]),p.print(' '));
        p.flush();
    }

    void nadji(int k,short p, int s){
        if (k==N+1){
            if (s>max) for (sl=0,max=s; sl<sa; l[sl]=a[sl++]);
            ok=N==sl;
            return;
        }
        if (s<dp[k]) return;
        dp[k]=s;
        short i=(short) (p+1);
        for (;i<=N; i++){
            if (mat[i][0]>=k){
                a[sa++]=(short) mat[i][2];
                nadji(k+1,i,s+mat[i][1]);
                sa--;
                if (ok) return;
            }
        }
        if (s>max) for (max=s,sl=0; sl<sa; l[sl]=a[sl++]);
    }

    void qsort(short a, short b){
        short i=a,j=b,m=(short) ((i+j)>>1);
        int[] t;
        for (;i<j;){
            for (;mat[i][0]<mat[m][0] || (mat[i][0]==mat[m][0] && mat[i][1]<mat[m][1]); i++);
            for (;mat[m][0]<mat[j][0] || (mat[m][0]==mat[j][0] && mat[m][1]<mat[j][1]); j--);
            if (i<=j){
                if (i<j){
                    t=mat[i];
                    mat[i]=mat[j];
                    mat[j]=t;
                }
                i++;
                j--;
            }
        }
        if (i<b) qsort(i,b);
        if (a<j) qsort(a,j);
    }

}

public class Timus1403 {
    public static void main(String[] args) throws IOException{
        new Courier();
    }
}