http://acm.hdu.edu.cn/showproblem.php?pid=1051
題目大意:
給n根木棍的長度和重量。根據要求求出製作木棍的最短時間。建立第一個木棍需要1分鐘,若是接着要製作的木棍重量和長度都比此木棍長就不需要建立的時間,若是沒有,則再需要建立時間。求時間最小爲多少。
解題思路:
對木棍的長度和重量進行排序,以長度爲首要考慮。排序完後的不一定都是下一根木棍重量和長度都大於前一根的。於是,我們對排序後的數組進行多次掃描,將可以在一次建立時間內完成的進行標記,知道木棍全部標記(設置一個外部變量來計數已掃描的元素的數量)。
例子:
5
4 9 5 2 2 1 3 5 1 4
排序完後:
1 4 2 1 3 5 4 9 5 2
然後進行第一次掃描:使用mark[]數組進行標記,mark[]初始化爲0,紅色爲第一次描過的。
Stiks: (1 4) (2 1) (3 5) (4 9) (5 2)
Mark: 1 0 1 1 0
這是的setuptime爲建立第一根木棍所要的時間,即1,此時掃描計數爲3
接着進行第二次掃描,藍色爲第二次掃描過的結果。
Stiks: (1 4) (2 1) (3 5) (4 9) (5 2)
Mark: 1 0 1 1 0
這是的setuptime爲1,此時掃描計數爲5
代碼如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Node implements Comparable<Node>{
int length;
int weight;
public Node(int length,int weight) {
this.length = length;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
if(this.length > o.length){
return 1;
}
else if( this.length == o.length){
if(this.weight > o.weight){
return 1;
}else{
return -1;
}
}
return -1;
}
}
public class HDU1051 {
List<Node> list = new ArrayList<Node>();
boolean mark[];
public void solve(){
Scanner sc = new Scanner(System.in);
int co = sc.nextInt();
for(int i=0; i<co; i++){
int an = 0;
list.clear();
int marknum = 0;
int n = sc.nextInt();
mark = new boolean[n];
for(int j=0; j<n; j++){
int l = sc.nextInt(),w = sc.nextInt();
Node node = new Node(l,w);
list.add(node);
}
Collections.sort(list);
while(marknum != n ){
Node temp = new Node(-1,-1);
an ++;
for(int j=0; j<list.size(); j++){
if( !mark[j]){
Node node = list.get(j);
if(node.weight >= temp.weight){
mark[j] = true;
temp = node;
marknum ++;
}
}
}
}
System.out.println(an);
}
}
public static void main(String[] args) {
new HDU1051().solve();
}
}