Hdu2647 逆向拓扑_发奖金

来源:互联网 发布:如何使淘宝店流量增加 编辑:程序博客网 时间:2024/04/29 08:19


题意:多个测试数据,每个测试数据第一行包含两个数n、m,代表有n个人,每个人最少发的奖金是888,现有m个要求,

有m行a和b,表示a要求比b的奖金多。

问能否满足所有的要求,如果能,则n个人得到的奖金总和最少是多少,不能满足所有要求就输出-1。


import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.StreamTokenizer;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;/** * @author YouYuan * @eMail E-mail:1265161633@qq.com * @Time 创建时间:2015年8月11日 下午4:36:35 * @Explain 说明:使用邻接表构图,节省内存开销 */public class Hdu2647逆向拓扑_发奖金 {static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));static int nextInt() throws IOException { in.nextToken(); return (int)in.nval;}static List<ArrayList<Integer>> arc = new ArrayList<ArrayList<Integer>>();//存储图的邻接表static int[] degree;//存储入度static int n, m;public static void main(String[] args) throws IOException {while(in.nextToken() != in.TT_EOF) {n = (int) in.nval;m = nextInt();initialise();structure();topologySort();}}/** * 拓扑排序 */private static void topologySort() {int[] salary = new int[n+1];//工资需要增加的数量Queue<Integer> queue = new LinkedList<Integer>();int sum = 0;//入度为0的总数int pay = 0;//增加的工资总数for (int i = 1; i <= n; i++) {if (degree[i] == 0) {queue.add(i);//所有度为0的顶点入队}}while(!queue.isEmpty()) {int index = queue.poll();//入度为0的下标,即b的下标sum++;for(int i : arc.get(index)) {degree[i]--;//以b为前驱的所有顶点入度-1if (degree[i] == 0) {queue.add(i);salary[i] = salary[index] + 1;//a的工资=b的工资+1pay += salary[i];//记录需要添加的工资总数}}}//sum!=n代表图中还有数据未处理(有环),无解out.println(sum != n ? -1 : (pay + n * 888));out.flush();}/** * 初始化 */private static void initialise() {arc.clear();for (int i = 0; i <= n; i++) {arc.add(new ArrayList<Integer>());}degree = new int[n+1];}/** * 构建图 * @throws IOException */private static void structure() throws IOException {while(--m>=0) {int a = nextInt();int b = nextInt();//a要求工资比b多,b指向a,所以建图时反过来if (!arc.get(b).contains(a)) {//去除重复数据arc.get(b).add(a);degree[a]++;}}}}


0 0
原创粉丝点击