*[topcoder]GUMIAndSongsDiv1

http://community.topcoder.com/stat?c=problem_statement&pm=12706&rd=15700

这题有意思。首先要观察到,如果选定一些歌曲,最优做法就是,按照tone排序,那么这时浪费的间隔最少,是(max_tone-min_tone)。那么首先对歌曲按照tone排序,这时由于取得顺序就是从左往右,可以用DP。(比如:http://community.topcoder.com/stat?c=problem_solution&cr=23061369&rd=15700&pm=12706)但又其实对于给定的歌曲集,用贪心按照duration从小到大取就行,那么用n*n来遍历歌曲集的选取,然后用贪心选至超过T就行了。

import java.util.*;



class Song {

    int duration;

    int tone;

    public Song(int duration, int tone) {

        this.duration = duration;

        this.tone = tone;

    }

}



public class GUMIAndSongsDiv1 {

    public int maxSongs(int[] duration, int[] tone, int T) {

        int len = duration.length;

        Song[] songs = new Song[len];

        for (int i = 0; i < len; i++) {

            songs[i] = new Song(duration[i], tone[i]);

        }

        Arrays.sort(songs, new Comparator<Song>() {

            public int compare(Song a, Song b) {

                return a.tone - b.tone;

            }

        });

        int res = 0;

        for (int first = 0; first < len; first++) {

            for (int last = first; last < len; last++) {

                Song[] tmp = new Song[last - first + 1];

                System.arraycopy(songs, first, tmp, 0, tmp.length);

                int timeLeft = T - (songs[last].tone - songs[first].tone);

                Arrays.sort(tmp, new Comparator<Song>() {

                    public int compare(Song a, Song b) {

                        return a.duration - b.duration;

                    }

                });

                int cnt = 0;

                for (int i = 0; i < tmp.length; i++) {

                    if (tmp[i].duration <= timeLeft) {

                        cnt++;

                        timeLeft -= tmp[i].duration;

                    }

                }

                res = Math.max(res, cnt);

            }

        }

        return res;

    }

}

  

你可能感兴趣的:(topcoder)