hdu-2647 反向图拓扑排序 java

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10492    Accepted Submission(s): 3358


Problem Description
Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
 

Input
One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
 

Output
For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.
 

Sample Input
 
      
2 1 1 2 2 2 1 2 2 1
 

Sample Output
 
      
1777 -1
 
这题主要是数据太大,不能开这么大的数组,而JAVA里面不能用泛型数组,这里取了点巧,用个类来装个容器,开了个类数组,避开了无法创建泛型数组这个问题
package 拓扑排序;

import java.util.*;

class Ed{
	List<Integer> edge=new ArrayList<>();
}
public class Main {
	static int num_person;
	static int num;
	static int[] enter;
	static Ed[] edge;
	static List<Integer> list;
	static List<Integer> temp;
	static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		while (sc.hasNext()) {
			num_person = sc.nextInt();
			num = sc.nextInt();
			init();
			tofoSort();
		}
	}

	public static void init() {
		enter = new int[num_person+1];
		list=new ArrayList<>();
		temp=new ArrayList<>();
		edge=new Ed[num_person+1];
		for(int i=0;i<edge.length;i++) {
			edge[i]=new Ed();
		}
		for (int i = 1; i <=num; i++) {
			int from = sc.nextInt();
			int to = sc.nextInt();
			if (!edge[to].edge.contains(from)) {
				edge[to].edge.add(from);
				enter[from]++;
			}
		}
	}

	public static void tofoSort() {
		int count=0;
		while(count!=num_person) {
			for (int j = 1; j <= num_person; j++) {
				if (enter[j] == 0) {
					temp.add(j);
					count++;
				}
			}
			if (temp.size()==0) {
				System.out.println(-1);
				return;
			} else {
				list.add(temp.size());
				for(int j=0;j<temp.size();j++) {
					int from=temp.get(j);
					enter[from]=-1;
					for(int k=0;k<edge[from].edge.size();k++) {
						enter[edge[from].edge.get(k)]--;
					}
				}
				temp.clear();
			}
		}
		int ans=0;
		for(int i=0;i<list.size();i++) {
			ans+=(i+888)*list.get(i);
		}
		System.out.println(ans);
	}

}

猜你喜欢

转载自blog.csdn.net/KingYMxe/article/details/78961920
今日推荐