博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法笔记_145:拓扑排序的应用(Java)
阅读量:7174 次
发布时间:2019-06-29

本文共 2915 字,大约阅读时间需要 9 分钟。

目录

 


1 问题描述

给出一些球,从1~N编号,他们的重量都不相同,也用1~N标记加以区分(这里真心恶毒啊,估计很多WA都是因为这里),然后给出一些约束条件,< a , b >要求编号为 a 的球必须比 b 轻,现在要求按编号升序输出每个球的重量,如果有多种解,输出字典序最小的那个。

例如:

input:

1

5 4

5 1
4 2
1 3
2 3

output:

2 4 5 3 1

 


2 解决方案

具体代码如下:

 

package com.liuzhen.practice;import java.util.ArrayList;import java.util.Scanner;public class Main {    public static int count;   //顶点的编号    public static int[] degree;   //计算顶点的入度    public static ArrayList
[] map; //表示图 public static ArrayList
result1 = new ArrayList
(); static class edge { public int a; //边的起点 public int b; //边的终点 public edge(int a, int b) { this.a = a; this.b = b; } } @SuppressWarnings("unchecked") public void init(int n) { count = n; degree = new int[n + 1]; map = new ArrayList[n + 1]; for(int i = 0;i <= n;i++) { map[i] = new ArrayList
(); degree[i] = 0; } return; } public String getResult() { String result = ""; int[] ans = new int[degree.length]; while(count >= 1) { int i = degree.length - 1; for(;i >= 1;i--) { if(degree[i] == 0) { ans[i] = count--; degree[i]--; for(int j = 0;j < map[i].size();j++) degree[map[i].get(j).b]--; break; } } if(i == 0) //此时给定图存在回环 return "-1"; } StringBuilder temp = new StringBuilder(""); for(int i = 1;i < ans.length;i++) { temp.append(ans[i]); if(i != ans.length - 1) temp.append(" "); } result = temp.toString(); return result; } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); int t = in.nextInt(); //要输入图的个数 while(t > 0) { t--; int n = in.nextInt(); test.init(n); int k = in.nextInt(); //输入图的边的个数 for(int i = 0;i < k;i++) { int a = in.nextInt(); int b = in.nextInt(); boolean judge = true; for(int j = 0;j < map[b].size();j++) { //检查重复边 if(map[b].get(j).b == a){ judge = false; break; } } if(judge && a != b) { map[b].add(new edge(b, a)); degree[a]++; //顶点a的入度自增1 } } result1.add(test.getResult()); } for(int i = 0;i < result1.size();i++) { System.out.println(result1.get(i)); } }}

 

运行结果:

25 45 14 21 32 310 54 18 17 84 12 82 4 5 3 15 1 6 2 7 8 3 4 9 10

 

 

 

 

 

参考资料:

   1. 

 

转载地址:http://hlbzm.baihongyu.com/

你可能感兴趣的文章
数据库设计的三范式
查看>>
PDO方法连接数据库(怕忘记,记起来)
查看>>
Gulan查询UI排布
查看>>
技术贴:asp.net实现唯一账户在线 禁止同一帐号同时在线 asp.net实现您的帐号在别处登录,您已被迫下线!...
查看>>
详解索引连接类型
查看>>
【剑道】用语中日对照
查看>>
UPNP
查看>>
.NET/ASP.NETMVC 深入剖析 Model元数据、HtmlHelper、自定义模板、模板的装饰者模式(二)...
查看>>
Salience Model
查看>>
是新浪移动云
查看>>
centos安装tomcat7
查看>>
php根据身份证号码计算年龄
查看>>
[转]关于position 的 static、relative、absolute、fixed、inherit
查看>>
[转]SSIS cannot convert between unicode and non-unicode string
查看>>
【原创】构建高性能ASP.NET站点 第七章 如何解决内存的问题(前篇)—托管资源优化—垃圾回收机制深度剖析...
查看>>
通过orderby关键字,LINQ可以实现升序和降序排序。LINQ还支持次要排序。
查看>>
Flume-0.9.4数据插入HBase-0.96
查看>>
二八定律全面分析SEO全过程
查看>>
JSON未定义
查看>>
背包整理(1) 01,完全,多重
查看>>