集装箱运输货物时,我们必须特别小心,不能把不相容的货物装在一只箱子里。比如氧化剂绝对不能跟易燃液体同箱,否则很容易造成爆炸。 本题给定一张不相容物品的清单,需要你检查每一张集装箱货品清单,判断它们是否能装在同一只箱子里。

输入格式:

输入第一行给出两个正整数:N (≤10​4​​) 是成对的不相容物品的对数;M (≤100) 是集装箱货品清单的单数。 随后数据分两大块给出。第一块有 N 行,每行给出一对不相容的物品。第二块有 M 行,每行给出一箱货物的清单,格式如下:

K G[1] G[2] … G[K]

其中 K (≤1000) 是物品件数,G[i] 是物品的编号。简单起见,每件物品用一个 5 位数的编号代表。两个数字之间用空格分隔。

输出格式:

对每箱货物清单,判断是否可以安全运输。如果没有不相容物品,则在一行中输出 Yes,否则输出 No

输入样例:

6 3
20001 20002
20003 20004
20005 20006
20003 20001
20005 20004
20004 20006
4 00001 20004 00002 20003
5 98823 20002 20003 20006 10010
3 12345 67890 23333

输出样例:

No
Yes
Yes

 对每一号物体,使用set存储与它不相容的物体,这样子在判断一堆物品是否相容的时候使用两层for循环遍历查找对于每一号物体它的不相容物体是否在这堆物品中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cstdio>
#include <vector>
#include <set>

using namespace std;

bool is_cluster(vector<set<int>> v, int g[], int k) {
for (int i = 0; i < k; i++) {
for (int j = i + 1; j < k; j++) {
if (i != j && v[g[i]].find(g[j]) != v[g[i]].end())return false;
}
}
return true;
}

int main() {
vector<set<int>> v(100010);
int n = 0, m = 0, a = 0, b = 0, k = 0;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
v[a].insert(b);
v[b].insert(a);
}
int g[1010];
for (int i = 0; i < m; i++) {
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &g[j]);
}
printf("%s\n", is_cluster(v, g, k) ? "Yes" : "No");
}
return 0;
}

子曰:“三人行,必有我师焉。择其善者而从之,其不善者而改之。” 本题给定甲、乙、丙三个人的能力值关系为:甲的能力值确定是 2 位正整数;把甲的能力值的 2 个数字调换位置就是乙的能力值;甲乙两人能力差是丙的能力值的 X 倍;乙的能力值是丙的 Y 倍。请你指出谁比你强应“从之”,谁比你弱应“改之”。

输入格式:

输入在一行中给出三个数,依次为:M(你自己的能力值)、X 和 Y。三个数字均为不超过 1000 的正整数。

输出格式:

在一行中首先输出甲的能力值,随后依次输出甲、乙、丙三人与你的关系:如果其比你强,输出 Cong;平等则输出 Ping;比你弱则输出 Gai。其间以 1 个空格分隔,行首尾不得有多余空格。 注意:如果解不唯一,则以甲的最大解为准进行判断;如果解不存在,则输出 No Solution

输入样例 1:

48 3 7

输出样例 1:

48 Ping Cong Gai

输入样例 2:

48 11 6

输出样例 2:

No Solution

已知甲是两位整数,所以可以从99到10的枚举,这样乙的值也就确定了,丙的值会稍微难确定一点。丙的值可以有两个条件可以确定,分别是甲乙两人能力差是丙的能力值的 X 倍和乙的能力值是丙的 Y 倍,可以用这个条件中的一个假设丙的值,用另一个条件去做验证。题目没有说明丙的整型的,所以要给丙定个浮点型的变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

void compare(int m, double x) {
if (m < x) printf(" Cong");
else if (m == x) printf(" Ping");
else printf(" Gai");
}

int main() {
int x = 0, y = 0, m = 0, flag = 0;
scanf("%d %d %d", &m, &x, &y);
for (int a = 99; a >= 10; a--) {
int b = a % 10 * 10 + a / 10;
double c = 1.0 / x * abs(a - b);
if (b == c * y) {
printf("%d", a);
compare(m, a);
compare(m, b);
compare(m, c);
flag = 1;
break;
}
}
if (flag == 0) {
printf("No Solution");
}
}

当自然数 n 依次取 1、2、3、……、N 时,算式 ⌊n/2⌋+⌊n/3⌋+⌊n/5⌋ 有多少个不同的值?(注:⌊x⌋ 为取整函数,表示不超过 x的最大自然数,即 x 的整数部分。)

输入格式:

输入给出一个正整数 N(2≤N≤10​4​​)。

输出格式:

在一行中输出题面中算式取到的不同值的个数。

输入样例:

2017

输出样例:

1480

一层for循环i从1到n,把i/2 + i/3 + i/n的值插入到set中,输出set的size就是不同值的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdio>
#include <set>

int main() {
int n = 0;
scanf("%d", &n);
std::set<int> s;
for (int i = 1; i <= n; i++) {
s.insert(i / 2 + i / 3 + i / 5);
}
printf("%d", s.size());
return 0;
}

做作业的时候,邻座的小盆友问你:“五乘以七等于多少?”你应该不失礼貌地围笑着告诉他:“五十三。”本题就要求你,对任何一对给定的正整数,倒着输出它们的乘积。

输入格式:

输入在第一行给出两个不超过 1000 的正整数 A 和 B,其间以空格分隔。

输出格式:

在一行中倒着输出 A 和 B 的乘积。

输入样例:

5 7

输出样例:

53

偷懒的用库函数去AC了。 a 和 b的乘积转换成字符串,然后将字符串翻转,最后将翻转过的字符串转换成数字就是答案。 PS: 图片是电影《放牛班的春天》的截图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstdio>
#include <string>
#include <algorithm>

using namespace std;

int main() {
int a = 0, b = 0;
scanf("%d %d", &a, &b);
string s = to_string(a * b);
reverse(s.begin(), s.end());
printf("%d", stoi(s));
return 0;
}

第 11 章 多线程

  • 简述线程的基本概念,程序、进程、线程的关系是什么。 线程与进程相似,但线程是一个比进程更小的执行单位。 程序是静态的代码,进程是程序的一次执行过程,是系统运行程序的基本单位;线程是进程的更小的划分
  • 什么是多线程?为什么程序的多线程功能是必要的? 多线程就是同事执行一个以上的线程,一个线程的执行不必等待另一个线程执行完后才执行,所有线程都可以发生在同一时刻;单一的进程在执行任务会出现资源空闲,采用多线程可以让CPU在同一个时间之内执行一个程序中得好几个程序段来完成工作
  • 多线程与多任务的差异是什么? 多任务是针对操作系统而言的 ,表示操作系统可以同事运行多个应用程序,而多线程是对一个进程而言的,表示在一个进程内部可以同时执行多个线程。
  • 线程有哪些基本状态?这些状态是如何定义的? 新建状态、就绪状态、阻塞状态、运行状态、消亡状态。 新建状态:线程对象已经被分配了内存空间和其他资源,并已被初始化,但是该线程尚未被调度。 就绪状态:处于新建状态的线程被启动后,将进入线程队列排队等待CPU时间片,此时它以具备了运行的条件。 运行状态:线程正在运行,并且已经拥有了对CPU的控制权 阻塞状态:正在执行的线程如果在某些特殊情况下 ,将让出CPU并暂时中止自己的执行 消亡状态:线程不再具有继续运行的能力
  • Java程序实现多线程有哪两个途径? 继承Thread类,实现Runnable接口
  • 在什么情况下必须以类实现Runnable接口来创建线程? 当类已经继承了一个类的时候,由于Java是单继承的,所以必须实现Runnable接口才能创建线程
  • 什么是线程的同步?程序中为什么要实现线程的同步?是如何实现同步的? 当一个线程对共享的数据进行操作时, 应使之成为一个”原子操作“,即在没有完成相关操作之前,不允许其他线程打断它,否则,就会破坏数据的完整性,必然会得到错误的处理结果;线程间的数据共享会导致多个线程同时处理数据而使数据出现不一致,所以要实现线程的同步;通过线程间互斥访问临界资源来实现同步。
  • 假设某家银行可接受顾客的汇款,每进行一次汇款,便可计算出汇款的总额。现有两名顾客,每人分三次、每次100元将钱汇入。试编程来模拟顾客的汇款操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Exercise {
public static void main(String[] args) {
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}
}

class Customer extends Thread {

@Override
public void run() {
for (int i = 0; i < 3; i++) {
Bank.deposit(100);
}
}
}

class Bank {
public static int balance = 0;

public synchronized static void deposit(int b) {
int temp = balance;
temp += b;
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {

}
balance = temp;
System.out.println("汇款之后" + balance);
}
}

第 12 章 泛型与容器类

  • 什么是泛型的类型参数?泛型的主要优点是什么?在什么情况下使用泛型方法?泛型类与泛型方法的主要区别是什么? 泛型所操作的数据类型被指定为一个参数,这个参数称为类型参数;泛型的主要优点是能够在编译时而不是在运行时检测出错误; 返回值类型和至少一个参数类型是泛型的情况下使用泛型方法;对于泛型方法,不需要把实际的类型传递给泛型方法,但泛型类却恰恰相反,即必须把实际的类型参数传递给泛型类

  • 在泛型中,类型通配符的主要作用是什么? 一是用在泛型类创建泛型对象时;二是用在方法的参数中

  • 分别件数LinkedList和ArrayList、HashSet与HashMap和TreeMap有何异同。 相同点:

    • LinkedList和ArrayList都实现了List接口
    • HashSet和TreeSet都实现了Set接口

    不同点:

    • LinkedList采用链表结构保存对象,使用双链表实现List。这种结构向链表中任意位置插入、删除元素时不需要移动其他元素,链表的的大小可以动态增长或减小的,但不具有随机存取特性
    • ArrayList数组列表类使用一维数组实现List,该类实现的是可变数组,允许所有元素,包括null。具有随机存取特性,插入、删除元素是需要移动其他元素,当元素很多时,插入、删除的速度较慢。在向ArrayList中添加元素时,其容量会自动增大,但不能自动缩小
    • HasetSet是根据哈希码来存取集合中的元素,集合中的元素是无序的
    • TreeSet还实现了SortedSet接口,集合中的元素都是有序的
  • 将1~10之间的整数存放到一个线性表LinkedList的对象中,然后将其下标为4的元素从列表中删除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.LinkedList;

public class Exercise {
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
for (int i = 1; i <= 10; i++) {
linkedList.add(i);
}
linkedList.remove(4);
for (Integer aLinkedList : linkedList) {
System.out.println(aLinkedList);

}
}
}
  • 利用ArrayList类创建一个对象,并向其添加若干个字符串型元素,然后随机选一个元素输出。
1
2
3
4
5
6
7
8
9
10
11
import java.util.ArrayList;

public class Exercise {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("Java");
System.out.println(arrayList.get((int) (Math.random() * (arrayList.size() - 1))));
}
}
  • 集合A={1,2,3,4}和B={1,3,5,7,9,11},编程求A与B的交集、并集和差集。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.HashSet;
import java.util.Set;

public class Exercise {
public static void main(String[] args) {
Set<Integer> a = new HashSet<>();
Set<Integer> b = new HashSet<>();
for (int i = 1; i <= 4; i++) {
a.add(i);
}
for (int i = 1; i <= 11; i += 2) {
b.add(i);
}
a.retainAll(b);
a.addAll(b);
a.remove(b);
}
}
  • 利用随机函数生成10个随机数,并将他们有序地存入到一个TreeSet对象中,然后利用迭代器有序地输出。
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.TreeSet;

public class Exercise {
public static void main(String[] args) {
TreeSet<Double> treeSet = new TreeSet<>();
for (int i = 0; i < 10; i++) {
treeSet.add(Math.random());
}
for (Double aTreeSet : treeSet) {
System.out.println(aTreeSet);
}
}
}
  • 利用HashMap类对象存储公司电话号码薄,其中包含公司的电话号码和公司名称,然后删除一个公司和查询一个公司的操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.HashMap;

public class Exercise {
public static void main(String[] args) {
HashMap<String, String> number = new HashMap<>();
number.put("A", "11111111");
number.put("B", "22222222");
number.put("C", "33333333");
number.put("D", "44444444");
number.remove("A");
System.out.println(number.containsKey("C"));
}
}

​  

第 13 章 图形界面设计

  • Swing组件分为哪三类? 容器类(container class)、辅助类(hepler class)和组件类(component class)
  • Swing的顶层容器包含哪些窗格?大部分的可见组件都放在哪个窗格中? JFrame、JApplet和JDialog;JFrame
  • 颜色类Color中提供了哪些表示颜色的变量? BLACK、BLUE、CYAN、DARK_GRAY、GRAY、GREEN、LIGHT_GRAY、MAGENTA、ORANGE、PINK、RED、WHITE、YELLOW
  • 字体类Font的主要用途有哪些? 设置组件所用字体的样式、大小与字形等属性。
  • 图标类ImageIcon的主要作用是什么?Java语言当前支持哪三种图像格式? 装饰组件;GIF、JPEG、PNG
  • Swing主要用来处理文字输入的组件有几个?这几组件有何不同? JTextField、JPasswordField、JTextArea 单行文本编辑组件JTextField、密码文本行组件JPasswordField、多行文本编辑组件JTextArea
  • 在将组件添加到窗口中时,为什么需将组件设置为不透明状态才能将其底色显示出来? 因为JFrame的框架一旦被创建,其中就已经包含了一个内容窗格,设置的JFrame背景颜色,仍然会被内容窗格遮盖,由框架内容窗格委托特性可知,在向JFrame中添加组件时,组件都加在了内容窗格中
  • 如何设置才能将窗口的底色显示出来? 通过调用JFrame的成员方法getContentPane()获得,然后再设置内容窗格的背景色,这样才能显示出窗口的背景色
  • 设计一个窗口,内含一个文本框、三个复选框、两个单选框、一个标签和一个按钮。各组件的位置、大小和其上的文字由用户自己设定。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.awt.FlowLayout;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Exercise {
public static void main(String[] args) {
JFrame window = new JFrame("A Windows");
window.setLayout(new FlowLayout());

JTextField textField = new JTextField(20);
window.add(textField);

JCheckBox checkBox1 = new JCheckBox("CheckBox1");
JCheckBox checkBox2 = new JCheckBox("CheckBox2");
JCheckBox checkBox3 = new JCheckBox("CheckBox3");
window.add(checkBox1);
window.add(checkBox2);
window.add(checkBox3);

JRadioButton radioButton1 = new JRadioButton("RadioButton1");
JRadioButton radioButton2 = new JRadioButton("RadioButton2");
ButtonGroup bg = new ButtonGroup();
bg.add(radioButton1);
bg.add(radioButton2);

window.add(radioButton1);
window.add(radioButton2);

JLabel label = new JLabel("This is a label");
window.add(label);

JButton button = new JButton("Button");
window.add(button);

window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
  • Java语言中常用的布局管理器有哪几个?它们各有什么特点? awt五种布局管理器,swing3种(其中两种不介绍) 流式布局管理器FlowLayout:流式页面设计,组件按照加入容器的先后顺序从左向右排列,一行排满之后就自动地转到下一行继续从左向右排列,每一行中得组件默认设置为剧中排列 边界式布局管理器BorderLayout:将显示区域分为东、西、南、北、中5个区域,在将组件加入容器时,指定把组件加入到哪个区域中,默认为中间区域 网格式布局管理器GridLayout:将容器的空间划分为若干行与列的网格形式,每个网格称为单元格,在容器上添加组件时,它们会按从左向右、从上到下的顺序在网格中排列。 卡片式布局管理器CardLayout:把容器中得所有组件如同堆叠起来的一副“扑克牌”,每次只能显示最上面的一张 网格包布局管理器GridBagLayout:是在网格布局管理器的基础上发展而来的,但GridBagLayout布局管理器中允许组件占用不同行或者不同咧的多个单元格,这些被占用的单元格称为组件的显示区域 盒式布局管理器BoxLayout:在一行或者一列中摆放组件

第 14 章 事件处理

  • 什么是事件?简述Java语言的委托事件模型。 所谓事件,就是用户使用鼠标或键盘对窗口中得组件进行交互时所发生的事情;委托事件模型就是组件将事件处理委托给外部的处理实体
  • 若要处理事件,就必须要有事件监听者,通常哪有对象可以担任监听者? 包含“事件源”的容器对象、内部类对象和匿名内部类都可以担任监听者
  • Java语言中处理事件的具体方法是什么?
    • 确认触发的事件,取得事件类的名字,如ActionEvent,去掉其中的“Event”字样,在剩下的部分加入“Listener”,这就是在类里需要实现的事件监听者接口
    • 实现上述的接口,针对想要捕获的事件编写方法代码。如要捕获单击按钮事件,就要为ActionListener接口中的actionPerformed()方法编写代码
    • 为事件监听者创建一个对象,让组件调用方法完成对它的注册,方法是在监听者接口的名字中加入一个前缀“add”,如addActionListener()
  • 在进行事件处理时,可以使用实现多个监听者接口的方式,也可以尽可能地使用继承适配器类的方式。使用适配器类的好处是什么? 当需要对某件事件进行处理时,只需让事件处理类继承事件所对应的适配器类,这样只需要覆盖本次操作用到的事件处理方法即可,而不必实现无关的事件处理方法
  • 设计一个窗口,在窗口内放置一个按钮,当不断地单击该按钮时,在其上显示它被单击的次数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Exercise {
public static void main(String[] args) {
new Window();
}
}

class Window extends JFrame {
private JButton button;
private int time;
private JLabel label;

public Window() {
button = new JButton("Click Me");
label = new JLabel("0");
label.setHorizontalAlignment(JLabel.CENTER);
time = 0;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
time++;
label.setText("" + time);
}
});
add(button, BorderLayout.SOUTH);
add(label, BorderLayout.NORTH);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
  • 设计一个窗口,在该窗口中添加一个JList组件,该组件中有5门课程名称的选项。然后再在窗口中添加一个文本区,当选择JList组件中的某个选项后,文本区中显示对该课程的介绍。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Exercise {
public static void main(String[] args) {
new Window();
}
}

class Window extends JFrame {

private static final long serialVersionUID = -2929177477951330739L;
private JList<String> courses;

public Window() {
String[] model = {"English", "Chinese", "C Programming Language", "Java Programming Language", "Operation System"};
courses = new JList<>(model);

JScrollPane scrollPane = new JScrollPane(courses);
add(scrollPane, BorderLayout.CENTER);

JTextArea textArea = new JTextArea();
textArea.setEditable(false);
add(textArea, BorderLayout.SOUTH);

courses.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
String s = courses.getSelectedValue();
switch (s) {
case "English":
textArea.setText("This is English");
break;
case "Chinese":
textArea.setText("This is Chinese");
break;
case "C Programming Language":
textArea.setText("This is C Programming Language");
break;
case "Java Programming Language":
textArea.setText("This is Java Programming Language");
break;
case "Operation System":
textArea.setText("This is Operation System");
break;
}
}
});

pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
  • 设计一个窗口,其中包含一个文本区、两个复选框和三个横向滑动条,其中滑动条用来调整R、G、B三色的分量从0~255的变化;两个复选框分别用于设定把滑动条调出的颜色应用于文本区的前景色还是背景色。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Exercise {
public static void main(String[] args) {
new Window();
}
}

class Window extends JFrame {

private static final long serialVersionUID = -4682287151007612144L;
JCheckBox frontGroundColor = new JCheckBox("frontGroundColor");
JCheckBox backGroundColor = new JCheckBox("backGroundColor");
JTextArea textArea = new JTextArea("选择前景色和背景色,滑动滑动条查看颜色变化", 20, 30);
JSlider rJSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
JSlider gJSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
JSlider bJSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);

public Window() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

add(textArea);

JPanel select = new JPanel();
select.setLayout(new FlowLayout());
select.add(frontGroundColor);
select.add(backGroundColor);
add(select);

JPanel colorPanel = new JPanel();
colorPanel.setLayout(new BoxLayout(colorPanel, BoxLayout.Y_AXIS));
colorPanel.add(rJSlider);
colorPanel.add(gJSlider);
colorPanel.add(bJSlider);
rJSlider.setMajorTickSpacing(30);
rJSlider.setMinorTickSpacing(3);
rJSlider.setPaintTicks(true);
rJSlider.setPaintLabels(true);
gJSlider.setMajorTickSpacing(30);
gJSlider.setMinorTickSpacing(3);
gJSlider.setPaintTicks(true);
gJSlider.setPaintLabels(true);
bJSlider.setMajorTickSpacing(30);
bJSlider.setMinorTickSpacing(3);
bJSlider.setPaintTicks(true);
bJSlider.setPaintLabels(true);
add(colorPanel);

backGroundColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (backGroundColor.isSelected()) {
textArea.setBackground(new Color(rJSlider.getValue(), gJSlider.getValue(), bJSlider.getValue()));
} else {
textArea.setBackground(new Color(255, 255, 255));
}
}
});

frontGroundColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (frontGroundColor.isSelected()) {
textArea.setForeground(new Color(rJSlider.getValue(), gJSlider.getValue(), bJSlider.getValue()));
} else {
textArea.setForeground(new Color(0, 0, 0));
}
}
});

rJSlider.addChangeListener(new ColorListen());
gJSlider.addChangeListener(new ColorListen());
bJSlider.addChangeListener(new ColorListen());

pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

class ColorListen implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
if (frontGroundColor.isSelected()) {
textArea.setForeground(new Color(rJSlider.getValue(), gJSlider.getValue(), bJSlider.getValue()));
}
if (backGroundColor.isSelected()) {
textArea.setBackground(new Color(rJSlider.getValue(), gJSlider.getValue(), bJSlider.getValue()));
}
}
}
}
  • 编写一应用程序,在其窗口内包含一个菜单栏和一个文本区。菜单栏包括“设置”和“操作”两个菜单。“操作”菜单包括“退出”菜单项,当用户选择“退出”菜单项时,则关闭窗口退出整个应用程序的运行;“设置”菜单包括“字体”和“风格”两个菜单项和一个“只读”复选菜单项。“字体”菜单项包括“宋体”、“楷体”和“黑体”3个单选子菜单项,“风格”菜单项包括“普通”、“黑体”、“斜体”3个复选子菜单项。当“只读”菜单项未被选中时,用户可以了文本区内输入字符;当“只读”菜单项被选中时,用户不能在文本区内输入字符。当用户选择其它菜单项时,文本区内的文字随之变化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;

public class Exercise {
public static void main(String[] args) {
new Window();
}
}

class Window extends JFrame {

private static final long serialVersionUID = -4682287151007612144L;
JTextArea textArea = new JTextArea(20, 30);

public Window() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

JMenuBar menuBar = new JMenuBar();
JMenu setting = new JMenu("Setting");
JMenu operating = new JMenu("Operating");
menuBar.add(setting);
menuBar.add(operating);

JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
operating.add(exit);

JMenu style = new JMenu("Style");
JMenu font = new JMenu("Font");
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButtonMenuItem ssti = new JRadioButtonMenuItem("宋体");
JRadioButtonMenuItem klti = new JRadioButtonMenuItem("楷体");
JRadioButtonMenuItem hzti = new JRadioButtonMenuItem("黑体");
buttonGroup.add(ssti);
buttonGroup.add(klti);
buttonGroup.add(hzti);
font.add(ssti);
font.add(klti);
font.add(hzti);
JCheckBoxMenuItem normal = new JCheckBoxMenuItem("正常");
JCheckBoxMenuItem black = new JCheckBoxMenuItem("黑体");
JCheckBoxMenuItem till = new JCheckBoxMenuItem("斜体");
style.add(normal);
style.add(black);
style.add(till);
JRadioButtonMenuItem readOnly = new JRadioButtonMenuItem("Read-Only");
setting.add(style);
setting.add(font);
setting.add(readOnly);

add(menuBar);

add(textArea);

readOnly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (readOnly.isSelected()) {
textArea.setEditable(false);
} else {
textArea.setEditable(true);
}
}
});

addText(normal);
addText(black);
addText(till);
addText(ssti);
addText(klti);
addText(hzti);
addText(readOnly);

setVisible(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void addText(JMenuItem item) {
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.append(item.getText() + "n");
}
});
}
}
  • 在上一题的基础上增加如下的功能:每当用户选中“只读”菜单项时,都将“字体”和“风格”两个菜单变成灰色,使之不能被选中;而每当“只读”菜单项未被选中时,再将“字体”和“风格”两个菜单项恢复成可选状态。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;

public class Exercise {
public static void main(String[] args) {
new Window();
}
}

class Window extends JFrame {

private static final long serialVersionUID = -4682287151007612144L;
JTextArea textArea = new JTextArea(20, 30);

public Window() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

JMenuBar menuBar = new JMenuBar();
JMenu setting = new JMenu("Setting");
JMenu operating = new JMenu("Operating");
menuBar.add(setting);
menuBar.add(operating);

JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
operating.add(exit);

JMenu style = new JMenu("Style");
JMenu font = new JMenu("Font");
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButtonMenuItem ssti = new JRadioButtonMenuItem("宋体");
JRadioButtonMenuItem klti = new JRadioButtonMenuItem("楷体");
JRadioButtonMenuItem hzti = new JRadioButtonMenuItem("黑体");
buttonGroup.add(ssti);
buttonGroup.add(klti);
buttonGroup.add(hzti);
font.add(ssti);
font.add(klti);
font.add(hzti);
JCheckBoxMenuItem normal = new JCheckBoxMenuItem("正常");
JCheckBoxMenuItem black = new JCheckBoxMenuItem("黑体");
JCheckBoxMenuItem till = new JCheckBoxMenuItem("斜体");
style.add(normal);
style.add(black);
style.add(till);
JRadioButtonMenuItem readOnly = new JRadioButtonMenuItem("Read-Only");
setting.add(style);
setting.add(font);
setting.add(readOnly);

add(menuBar);

add(textArea);

readOnly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (readOnly.isSelected()) {
textArea.setEditable(false);
style.setEnabled(false);
font.setEnabled(false);
} else {
textArea.setEditable(true);
style.setEnabled(true);
font.setEnabled(true);
}
}
});

addText(normal);
addText(black);
addText(till);
addText(ssti);
addText(klti);
addText(hzti);
addText(readOnly);

setVisible(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void addText(JMenuItem item) {
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.append(item.getText() + "n");
}
});
}
}

​  

第 16 章 小程序设计

  • Java小程序的基本工作原理是什么? 将编译好的小程序字节码文件,即.class文件保存在特定的WWW服务器上,在同一个或另一个WWW服务器上保存着嵌入有该字节码文件名的HTML文件。当某一个浏览器向服务器请求下载嵌入了小程序的HTML文件时,该文件中得信息以一定的格式显示在用户屏幕上。当浏览器遇到HTML文件中嵌有小程序的标志时,浏览器会根据这个小程序的名字和位置自动把字节码文件从WWW服务器上下载到本地,并利用浏览器本身拥有的Java解释器直接执行该字节码文件。
  • init()、start()、stop()、destory()是小程序中非常重要的4个方法,请问它们各自的调用时机和功能是什么? init()在小程序被创建时第一个调用的方法,它只运行一次,主要是用来对小程序设置初值用 start()调用完init()方法之后,就立即调用start()方法。只要小程序画面每出现一次,start()方法就会被调用一次。 stop()方法类似于start()方法的逆操作,当浏览器窗口失去焦点变为不活动状态、切换到其他网页浏览或是关闭浏览器时,需要停止小程序的运行,此时系统会自动调用stop()方法以暂停小程序的运行,所以stop()方法也可以被重复调用。 destory()当用户退出浏览器时,浏览器运行的小程序也将停止运行,释放内存。此时浏览器会自动调用小程序对象的destory()方法来完成一些释放资源、关闭连接之类的操作等。
  • 如何向小程序传递参数? 由HTML文件中得一个专门标记来完成的
  • 将Java的应用程序转换成小程序的主要步骤有哪些?
    • 制作一个HTML网页文件,带有响应的标记,从而能够下载小程序的代码
    • 声明一个类,使其继承JApplet类,并使其成为public类型
    • 在应用程序中去掉main()方法。
    • 在应用程序中,设置窗口的大小通过调用setSize()方法来实现
    • 小程序在浏览器退出时,它会终止
    • 如果在应用程序中使用setTitle()为窗口设置标题,那么在转换成小程序时此方法不能使用
    • 用init()方法替换构造方法,在浏览器创建这个小程序类的一个对象时,它调用了init()方法
  • 编写小程序,用paintComponent()方法显示一行字符串,小程序包含“方法”和“缩小”两个按钮。当单击“放大”按钮时,显示的字符串的字号方法一号;单击“缩小”按钮时,显示的字符串字号缩小一号。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JTextArea;

public class Exercise extends JApplet {

private static final long serialVersionUID = -6178049653652743932L;
private String s;
private JButton big;
private JButton smaller;
private int size = 16;
private JTextArea textArea;

@Override
public void init() {
s = "This is a string";
big = new JButton("放大");
smaller = new JButton("缩小");
textArea = new JTextArea(s);
textArea.setFont(new Font(s, Font.ITALIC, size));

Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(textArea);
c.add(big);
c.add(smaller);

big.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size++;
textArea.setFont(new Font(s, Font.ITALIC, size));
}
});
smaller.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size--;
textArea.setFont(new Font(s, Font.ITALIC, size));
}
});
}
}

​  

第 17 章 Java数据库程序设计

  • 写出在数据库StudentScore的Student表中查找所有年龄大于等于19的同学的SQL语句 SELECT * FROM StudentScore.Student WHERE age >= 19;

  • 写出姓名为“刘韵”的学生所学课程名称及成绩的SQL语句 SELECT cName, grade FROM Course, Score WHERE Course.cNo = Score.cNo AND sNo IN (SELECT sNo FROM Student WHERE sName = “刘韵”)

  • 描述JDBC中Driver、Connection、Statement和ResultSet接口的功能

    类或接口

    功能说明

    Driver

    驱动程序

    Connection

    数据库连接,负责与数据库键通讯,SQL执行以及食物处理都是在某个特定Connection环境下进行的。可以产生用以执行SQL的Statement对象

    Statement

    用以执行不含参数的静态SQL查询和更新,并返回执行结果

    ResultSet

    用以获得SQL查询结果

  • 使用Statement接口和PreparedStatement接口有什么区别? Statement接口用于执行不带参数的静态SQL语句;PreparedStatement是处理预编译语句的一个接口

  • 归纳一下使用JDBC进行数据库连接的完整过程 加载驱动程序、建立与数据库的连接、创建执行方式语句、执行SQL语句、处理返回结果和关闭创建的各种对象

  • 如何在结果集中返回字段的数据?如何在结果集中返回字段名? 使用ResultSet对象的getXXX()方法对结果集中得数据进行访问;

  • 编写一个应用程序,使其可以从StudentScore数据库的某个表中查询一个字段的所有信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.sql.*;

public class Exercise {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student", "user", "password");
Statement statement = connection.createStatement();
String sql = "select sno from student";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String sno = resultSet.getString("sno");
System.out.println(sno);
}
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

}
}
  • 创建一个名为Books的数据库,并在其中建立一个名为Book的表,字段包括书名、作者、出版社、出版时间和ISBN。编写一个应用程序,运用JDBC在该数据库中实现增加、删除和修改数据的功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Exercise {
public static void addRecord(Connection connection) {

String bookName = "h";
String author = "j";
String publisher = "j";
String publisherTime = "j";
String isbn = "k";

String sql = "INSERT INTO Books.Book(bookName, author, publisher, publisherTime, isbn) " +
"VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = null;
try {
connection.prepareStatement(sql);
preparedStatement.setString(1, bookName);
preparedStatement.setString(2, author);
preparedStatement.setString(3, publisher);
preparedStatement.setString(4, publisherTime);
preparedStatement.setString(5, isbn);
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}

public static void removeRecord(Connection connection) {
String bookName = "j";
String sql = "DROP FROM Books.Book WHERE bookName = ?";
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, bookName);
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void updateRecode(Connection connection) {
String bookName = "j";
String publisher = "k";
PreparedStatement preparedStatement = null;
String sql = "UPDATE Books.Book SET publisher = ? WHERE bookName = ?";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, publisher);
preparedStatement.setString(2, bookName);
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
  • 假设在StudentScore数据库的Studnet表中,存在多个姓氏相同的人,根据这种情况建立查询,要求提供一个合适的图形界面,用户可以滚动查看查询记录

 

第 18 章 Java网络编程

  • 什么是URL?URL地址由哪几部分组成? URL是统一资源定位符的英文缩写,它表示Internet上某一资源的地址;URL地址由5个部分组成,格式如下: 传输协议://主机名:端口号/文件名#引用
  • 什么是Socket?它与TCP/IP协议有何关系? Socket是实现 客户与服务器模式的通信方式,它首先需要建立稳定的连接,然后以流的方式传输数据,实现网络通信;Socket在TCP/IP中定义,针对一个特定的连接
  • 简述流式Socket的通信机制。它的最大特点是什么?为什么可以实现无差错通信? 建立两台计算机的连接,有一个程序向另一台计算机上的程序发送请求,建立通信;
  • 什么是端口号?服务器端和客户端分别如何使用端口号? 端口号是区分一台主机中得不同应用程序的一个数据标识符;服务器端和客户端必须为每个程序分配一个唯一的端口考,通过端口号指定要连接的那个程序
  • 什么是套接字?其作用是什么? 套接字是实现客户与服务器模式的通信模式,它首先需要建立稳定的连接,然后以流的方式传输数据,实现网络通信;套接字是网络上运行的两个程序间双向通信的一端,既可以接受请求,也可以发送请求,利用它可以较方便地进行网络上的数据传输。
  • 编写Java程序,使用InetAddress类实现根据域名自动到DNS(域名服务器)上查找IP地址的功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Exercise {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String dns = bufferedReader.readLine();
bufferedReader.close();
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName(dns);
System.out.println(inetAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Your Input Domain Can't Parse.");
}
}
}
  • 用Java程序实现流式Socket通信,需要使用那两个类?他们是如何定义的?应怎样使用? Socket类和ServerSocket类;Socket类用在客户端,用户通过创建一个Socket对象来建立与服务器的连接,ServerSocket类的作用是实现客户机/服务器模式的通信方法下服务器的套接字;客户端的程序使用Socket类建立一服务器的套接字连接,服务器端的程序使用ServerSocket类建立接受客户套接字的服务器套接字;
  • 与流式Socket相比,数据报通信有何特点? 数据报通信是无序的,也不能确保绝对安全可靠,但它非常简单,也具有比较高的效率

A gas station has to be built at such a location that the minimum distance between the station and any of the residential housing is as far away as possible. However it must guarantee that all the houses are in its service range. Now given the map of the city and several candidate locations for the gas station, you are supposed to give the best recommendation. If there are more than one solution, output the one with the smallest average distance to all the houses. If such a solution is still not unique, output the one with the smallest index number.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 positive integers: N (<= 103), the total number of houses; M (<= 10), the total number of the candidate locations for the gas stations; K (<= 104), the number of roads connecting the houses and the gas stations; and DS, the maximum service range of the gas station. It is hence assumed that all the houses are numbered from 1 to N, and all the candidate locations are numbered from G1 to GM. Then K lines follow, each describes a road in the format P1 P2 Dist where P1 and P2 are the two ends of a road which can be either house numbers or gas station numbers, and Dist is the integer length of the road.

Output Specification:

For each test case, print in the first line the index number of the best location. In the next line, print the minimum and the average distances between the solution and all the houses. The numbers in a line must be separated by a space and be accurate up to 1 decimal place. If the solution does not exist, simply output “No Solution”.

Sample Input 1:

4 3 11 5
1 2 2
1 4 2
1 G1 4
1 G2 3
2 3 2
2 G2 1
3 4 2
3 G3 2
4 G1 3
G2 G1 1
G3 G2 2

Sample Output 1:

G1
2.0 3.3

Sample Input 2:

2 1 2 10
1 G1 9
2 G1 20

Sample Output 2:

No Solution

题目要求找到一个加油站,这个加油站既要能够在规定的距离范围内服务所有的居民点,又要距离最近的居民点尽可能的远。如果存在多个,就选择距离所有居民点的平均距离最近的加油站。如果还存在多个,就选择加油站下标最小的一个。 规定0~N - 1为居民点,N ~ N + M- 1为加油站,用图数据结构表示,图的大小为(n + m) * (n + m)。 这里我用Dijkstra得到每一个加油站到其他居民点或其他加油站的距离dist,如果在dist的0~N中,存在dist[i] > ds(ds是加油站的最远服务距离),那么这个加油站就不满足条件的。如果最后都找不到加油站就输出No Solution。 用Dijkstra实现的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <cmath>

using namespace std;

const int inf = 999999;

int **graph;
bool *isVisited;
int *dist;

void initGraph(int n, int m) {
graph = new int *[n + m];
for (int i = 0; i < n + m; i++) {
graph[i] = new int[n + m];
for (int j = 0; j < n + m; j++) {
graph[i][j] = inf;
}
}
}

int toInt(char *p, int n) {
int num = 0, start = 0;
if (p[0] == 'G') start = 1;
for (int i = start; i < strlen(p); i++) {
num = num * 10 + p[i] - '0';
}
if (p[0] == 'G') return num - 1 + n;
else return num - 1;
}

void initStatus(int n, int m) {
if (isVisited == NULL) {
isVisited = new bool[n + m];
}
if (dist == NULL) {
dist = new int[n + m];
}
for (int i = 0; i < n + m; i++) {
isVisited[i] = false;
dist[i] = inf;
}
}

int findMinDist(int n, int m) {
int min = 0;
for (int i = 1; i < n + m; i++) {
if (isVisited[min] || (!isVisited[i] && dist[min] > dist[i])) {
min = i;
}
}
if (isVisited[min]) return -1;
else return min;
}

void dijkstra(int s, int n, int m) {
dist[s] = 0;
while (true) {
s = findMinDist(n, m);
if (s == -1) {
break;
}
isVisited[s] = true;
for (int i = 0; i < n + m; i++) {
if (dist[i] > dist[s] + graph[s][i]) {
dist[i] = dist[s] + graph[s][i];
}
}
}
}

void updateG(int g, int ds, int n, int &finalG, double &min, double &aver) {
double tmin = inf, taver = 0;
for (int i = 0; i < n; i++) {
if (dist[i] > ds || dist[i] == inf) {
return;
}
if (dist[i] < tmin) {
tmin = dist[i];
}
taver += dist[i] * 1.0 / n;
}


if (tmin > min) {
min = tmin;
aver = taver;
finalG = g;
} else if (abs(tmin - min) <= 0.00001) {
if (taver < aver) {
aver = taver;
finalG = g;
}
}
}

int main() {
int n = 0, m = 0, k = 0, ds = 0, temp = 0;
scanf("%d %d %d %d", &n, &m, &k, &ds);
initGraph(n, m);
for (int i = 0; i < k; i++) {
char p1[6], p2[6];
scanf("%s %s %d", p1, p2, &temp);
int p1i = toInt(p1, n);
int p2i = toInt(p2, n);
graph[p1i][p2i] = graph[p2i][p1i] = temp;
}
int finalG = n + m;
double min = -1, aver = inf;
for (int i = n; i < n + m; i++) {
initStatus(n, m);
dijkstra(i, n, m);
updateG(i, ds, n, finalG, min, aver);
}
if (finalG == n + m) {
printf("No Solution\n");
} else {
printf("G%d\n", finalG - n + 1);
printf("%.1f %.1f\n", min, aver);
}
return 0;
}

Excel can sort records according to any column. Now you are supposed to imitate this function.

Input Specification:

Each input file contains one test case. For each case, the first line contains two integers N (≤10​5​​) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student’s record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).

Output Specification:

For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID’s; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID’s in increasing order.

Sample Input 1:

3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

Sample Output 1:

000001 Zoe 60
000007 James 85
000010 Amy 90

Sample Input 2:

4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98

Sample Output 2:

000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60

Sample Input 3:

4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90

Sample Output 3:

000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90

列表排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

struct Record {
int id, grade;
char *name = new char[9];
};

void sortByThree(struct Record *records, int n) {
qsort(records, n, sizeof(records[0]), [](const void *a, const void *b) {
const struct Record arg1 = *static_cast<const struct Record * > (a);
const struct Record arg2 = *static_cast<const struct Record * > (b);

if (arg1.grade > arg2.grade) return 1;
if (arg1.grade < arg2.grade) return -1;
if (arg1.id > arg2.id) return 1;
return -1;
});
}

void sortByTwo(struct Record *records, int n) {
qsort(records, n, sizeof(records[0]), [](const void *a,
const void *b) {
const struct Record arg1 = *static_cast<const struct Record * > (a);
const struct Record arg2 = *static_cast<const struct Record * > (b);

if (strcmp(arg1.name, arg2.name) > 0) return 1;
if (strcmp(arg1.name, arg2.name) < 0) return -1;
if (arg1.id > arg2.id) return 1;
return -1;
});
}

void sortByOne(struct Record *records, int n) {
qsort(records, n, sizeof(records[0]), [](const void *a,
const void *b) {
const struct Record arg1 = *static_cast<const struct Record * > (a);
const struct Record arg2 = *static_cast<const struct Record * > (b);

if (arg1.id > arg2.id) return 1;
return -1;
});
}

int main() {
int n = 0, c = 0;
scanf("%d %d", &n, &c);
struct Record *records = new struct Record[n];
for (int i = 0; i < n; i++) {
scanf("%d %s %d", &records[i].id, records[i].name, &records[i].grade);
}
switch (c) {
case 1:
sortByOne(records, n);
break;
case 2:
sortByTwo(records, n);
break;
default:
sortByThree(records, n);
break;
}

for (int i = 0; i < n; i++) {
printf("%06d %s %d\n", records[i].id, records[i].name, records[i].grade);
}

delete[] records;
return 0;
}

People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

Input Specification:

Each input file contains one test case which occupies a line containing the three decimal color values.

Output Specification:

For each test case you should output the Mars RGB value in the following format: first output #, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0 to its left.

Sample Input:

15 43 71

Sample Output:

#123456

简单题,使用除法和取余

1
2
3
4
5
6
7
8
9
#include <cstdio>

int main() {
char sign[] = "0123456789ABC";
int a = 0, b = 0, c = 0;
scanf("%d %d %d", &a, &b, &c);
printf("#%c%c%c%c%c%c", sign[a / 13], sign[a % 13], sign[b / 13], sign[b % 13], sign[c / 13], sign[c % 13]);
return 0;
}

Programming Ability Test (PAT) is organized by the College of Computer Science and Technology of Zhejiang University. Each test is supposed to run simultaneously in several places, and the ranklists will be merged immediately after the test. Now it is your job to write a program to correctly merge all the ranklists and generate the final rank.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number N (≤100), the number of test locations. Then N ranklists follow, each starts with a line containing a positive integer K (≤300), the number of testees, and then K lines containing the registration number (a 13-digit number) and the total score of each testee. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first print in one line the total number of testees. Then print the final ranklist in the following format:

registration_number final_rank location_number local_rank

The locations are numbered from 1 to N. The output must be sorted in nondecreasing order of the final ranks. The testees with the same score must have the same rank, and the output must be sorted in nondecreasing order of their registration numbers.

Sample Input:

2
5
1234567890001 95
1234567890005 100
1234567890003 95
1234567890002 77
1234567890004 85
4
1234567890013 65
1234567890011 25
1234567890014 100
1234567890012 85

Sample Output:

9
1234567890005 1 1 1
1234567890014 1 2 1
1234567890001 3 1 2
1234567890003 3 1 2
1234567890004 5 1 4
1234567890012 5 2 2
1234567890002 7 1 5
1234567890013 8 2 3
1234567890011 9 2 4

先将每个地区的被测试者先排序得到一个地区的排名,然后将所有的被测试者进行排序,产生一个总排名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>

using namespace std;

struct testee {
char number[15];
int score, locnum, locrnk;
};

bool cmp(testee a, testee b) {
if (a.score > b.score) return true;
if (a.score < b.score) return false;
return strcmp(a.number, b.number) < 0;
}

int main() {
int n = 0;
scanf("%d", &n);
vector<struct testee> v;
for (int i = 1; i <= n; i++) {
int k = 0;
scanf("%d", &k);
for (int j = 0; j < k; j++) {
struct testee t;
scanf("%s %d", t.number, &t.score);
t.locnum = i;
v.push_back(t);
}
sort(v.end() - k, v.end(), cmp);
v[v.size() - k].locrnk = 1;
int rank = 2;
for (int j = (int) v.size() - k + 1; j < v.size(); j++) {
if (v[j].score == v[j - 1].score) v[j].locrnk = v[j - 1].locrnk;
else v[j].locrnk = rank;
rank++;
}
}
sort(v.begin(), v.end(), cmp);
printf("%lu\n", v.size());
int rank = 1;
for (int i = 0; i < v.size(); i++) {
if (i > 0 && v[i].score != v[i - 1].score) rank = i + 1;
printf("%s %d %d %d\n", v[i].number, rank, v[i].locnum, v[i].locrnk);
}
return 0;
}

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again! Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line “Yes” if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or “No” if not. Then in the next line, print the doubled number.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

判断一个k位数的两倍是不是原来那个数各个位数的全排列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdio>
#include <cstring>

int main() {
char s[22];
scanf("%s", s);
int *pers = new int[10], temp = 0, *pree = new int[10];
for (int i = strlen(s) - 1; i >= 0; i--) {
pers[s[i] - '0']++;
temp += 2 * (s[i] - '0');
s[i] = temp % 10 + '0';
pree[s[i] - '0']++;
temp /= 10;
}
if (temp != 0) pree[temp + '0']++;
bool state = true;
for (int i = 1; i <= 9; i++) {
if (pers[i] != pree[i]) {
state = false;
}
}
printf("%s\n", state ? "Yes" : "No");

if (temp != 0) printf("%d", temp);
printf("%s", s);
delete[] pree;
delete[] pers;
return 0;
}
0%