1 问题描述

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

例如:

input:

1

5 4

5 1

4 2

1 3

2 3

output:

2 4 5 3 1

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<edge>[] map; //表示图
public static ArrayList<String> result1 = new ArrayList<String>(); 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<edge>();
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));
}
}
}

运行结果:

4
1
2
3
3
5
1
1
8
1
8
4 5 3 1
1 6 2 7 8 3 4 9 10

最新文章

  1. SQL Server-聚焦使用索引和查询执行计划(五)
  2. jQuery系列之操作select标签
  3. VC++中开发汇编语言(转)
  4. iOS 阶段学习第11天笔记(OC基础知识)
  5. mysql之触发器入门
  6. MySQL 函数积累
  7. fcntl函数加文件锁
  8. AngularJS进阶(二)AngularJS路由问题解决
  9. 全面认识openstack:OpenStack架构详解
  10. Java API获取consumer group最新提交位移的时间
  11. 安装redis时Newer version of jemalloc required错误解决
  12. July 10th, Week 29th Sunday, 2016
  13. Unity shader学习之半兰伯特光照模型
  14. Maven中项目的启动
  15. CentOs - 使用ssh key远程登录
  16. 清华集训2015-Day 2
  17. [android] 网络断开的监听
  18. IntelliJ IDEA自定义类和方法注解模板
  19. 转转转--Java File和byte数据之间的转换
  20. EM最大期望算法

热门文章

  1. 最近常问的99道Java多线程面试题 !
  2. springMVC 重定向带参数
  3. C# winform DataGridView 绑定数据的的几种方法
  4. redis集群复制和故障转移
  5. UVALive 3295
  6. 带你学够浪:Go语言基础系列 - 8分钟学基础语法
  7. CentOS7搭建Java环境(JDK、MySQL和Tomcat)
  8. VMware Workstation如何修改弹出释放快捷键
  9. Spring Boot 开发集成 WebSocket,实现私有即时通信系统
  10. springmvc-初次接触