Cho n thành phố, hãy tô màu các thành phố này sao cho không có bất kỳ hai thành phố
nào kề nhau được tô cùng một màu và số màu được tô là ít nhất có thể.
Dữ liệu vào được lưu trên một trận vuông cij.
Nếu cij = 1 thì hai thành phố i,j là kề nhau, cij=0 thì hai thành phố i,j không kề nhau.
Bài toán tô màu là bài toán thuộc lớp bài toán NP-Đầy đủ.
TH4-02.CPP
Lập trình thuật toán tham lam (thuật toán tham khảo DSATUR) giải bài tô màu đồ thị; file
input được cho bởi file colorx.txt
Assistant
User
TH4-02.py
Assistant
Đây là đoạn mã Python tương tự để giải bài toán tô màu đồ thị bằng thuật toán tham lam DSATUR:
User
File "c:\Users\phanb\Downloads\python3\TH4-01.py", line 4
with open(“color1.txt”, “r”) as f:
^
SyntaxError: invalid character '“' (U+201C)
Assistant
Lỗi này xảy ra vì bạn đã sử dụng ký tự “ và ” để đặt tên cho file thay vì sử dụng ký tự " như bình thường. Khi sử dụng các ký tự này, Python sẽ không hiểu là đây là ký tự " và sẽ báo lỗi.
Bạn chỉ cần thay thế các ký tự “ và ” bằng ký tự " thì chương trình sẽ chạy bình thường:
with open("color1.txt", "r") as f:
Lưu ý là bạn cần kiểm tra xem tên file đúng hay chưa để chương trình có thể hoạt động.
User
File "c:\Users\phanb\Downloads\python3\TH4-01.py", line 58
print(“Total colors:”, np.amax(color) + 1)
^
SyntaxError: invalid character '“' (U+201C)
PS C:\Users\phanb\Downloads\python3>
Assistant
Lỗi này cũng tương tự như lỗi trước đó, bạn đã sử dụng ký tự “ và ” thay vì ký tự ".
Bạn chỉ cần thay thế các ký tự “ và ” bằng ký tự " và chương trình sẽ chạy bình thường:
print("Total colors:", np.amax(color) + 1)
Lưu ý là bạn cần kiểm tra lại toàn bộ mã lệnh để đảm bảo không còn sử dụng các ký tự “ và ” nữa.
User
fix toàn bộ code
import numpy as np
def input_data():
with open("color1.txt", "r") as f:
n = int(f.readline())
graph = []
for i in range(n):
graph.append(list(map(int, f.readline().split())))
return n, np.array(graph)
def degree(graph, u):
return np.sum(graph[u,:])
def find_max_dsatur(graph, color, colored, saturation):
max_saturation = -1
max_dsatur = -1
for i in range(graph.shape[0]):
if color[i] == -1:
saturation[i] = 0
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] += 1
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] == -1:
saturation[i] += 1
if saturation[i] > max_saturation or (saturation[i] == max_saturation and degree(graph, i) > degree(graph, max_dsatur)):
max_saturation = saturation[i]
max_dsatur = i
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] -= 1
return max_dsatur
Assistant
Đoạn mã của bạn đã được sửa lại như sau:
import numpy as np
def input_data():
with open("color1.txt", "r") as f:
n = int(f.readline())
graph = []
for i in range(n):
graph.append(list(map(int, f.readline().split())))
return n, np.array(graph)
def degree(graph, u):
return np.sum(graph[u,:])
def find_max_dsatur(graph, color, colored, saturation):
max_saturation = -1
max_dsatur = -1
for i in range(graph.shape[0]):
if color[i] == -1:
saturation[i] = 0
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] += 1
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] == -1:
saturation[i] += 1
if saturation[i] > max_saturation or (saturation[i] == max_saturation and degree(graph, i) > degree(graph, max_dsatur)):
max_saturation = saturation[i]
max_dsatur = i
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] -= 1
return max_dsatur
def dsatur(graph):
color = np.full(graph.shape[0], -1)
colored = np.zeros(graph.shape[0], dtype=int)
saturation = np.zeros(graph.shape[0], dtype=int)
max_dsatur = np.argmax([degree(graph, i) for i in range(graph.shape[0])])
color[max_dsatur] = 0
count = 1
while count < graph.shape[0]:
u = find_max_dsatur(graph, color, colored, saturation)
available = np.where(colored == 0)[0]
k = len(available)
if k == 0:
color[u] = count
count += 1
else:
idx = available[0]
for i in range(1, k):
if degree(graph, available[i]) > degree(graph, idx):
idx = available[i]
color[u] = idx
colored[color[u]] = 1
return color
def output_data(color):
print("Total colors:", np.amax(color) + 1)
for i, c in enumerate(color):
print("Node", i, "-", "Color:", c + 1)
if __name__ == "__main__":
n, graph = input_data()
color = dsatur(graph)
output_data(color)
Giải thuật tham lam DSATUR (Degree of Saturation):
Tính độ bậc của mỗi đỉnh trong đồ thị (số đỉnh kề với nó).
Chọn một đỉnh có độ bậc lớn nhất và tô màu cho đỉnh đó với một màu bất kỳ.
Sắp xếp các đỉnh còn lại theo thứ tự giảm dần của độ bậc và bắt đầu từ đỉnh có độ bậc lớn nhất.
Với mỗi đỉnh, tính độ bậc của các đỉnh đã được tô cùng màu với nó (degree of saturation), đỉnh có độ bậc d saturation cao nhất được chọn để tô màu cho đỉnh đó.
Lặp lại bước 4 cho đến khi tất cả các đỉnh đều được tô màu.
Độ phức tạp: O(n^2logn)
Để giải quyết bài toán tô màu đồ thị, ta cần lưu trữ đồ thị dưới dạng ma trận 2 chiều và số lượng màu đã dùng để tô màu các đỉnh. Ta có thể dùng một mảng colors[i] để lưu màu của đỉnh i (với giá trị ban đầu là -1).
Để tính độ bậc của mỗi đỉnh, ta duyệt từng hàng của ma trận và đếm số 1 trong hàng đó (số đỉnh kề với đỉnh đang xét).
Dùng DSATUR để tô màu cho các đỉnh. Ta sẽ lưu trữ hai mảng colored[] và saturation[] để tính độ bậc của từng đỉnh và tìm đỉnh có degree of saturation cao nhất để tô màu cho nó.
TH4-02.CPP:
#include
#include
#include
#include
using namespace std;
const int MAXN = 100;
int n, color[MAXN], colored[MAXN], saturation[MAXN], graph[MAXN][MAXN];
void input() {
ifstream f("colorx.txt");
f >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
f >> graph[i][j];
}
}
f.close();
}
int degree(int u) {
int count = 0;
for (int i = 0; i < n; i++) {
if (graph[u][i] == 1) {
count++;
}
}
return count;
}
int find_max_dsatur() {
int max_saturation = -1, max_dsatur = -1;
for (int i = 0; i < n; i++) {
if (color[i] == -1) {
saturation[i] = 0;
for (int j = 0; j < n; j++) {
if (graph[i][j] == 1 && color[j] != -1) {
colored[color[j]]++;
}
}
for (int j = 0; j < n; j++) {
if (graph[i][j] == 1 && color[j] == -1) {
saturation[i]++;
}
}
if (saturation[i] > max_saturation || (saturation[i] == max_saturation && degree(i) > degree(max_dsatur))) {
max_saturation = saturation[i];
max_dsatur = i;
}
for (int j = 0; j < n; j++) {
if (graph[i][j] == 1 && color[j] != -1) {
colored[color[j]]--;
}
}
}
}
return max_dsatur;
}
void dsatur() {
for (int i = 0; i < n; i++) {
color[i] = -1;
colored[i] = 0;
saturation[i] = 0;
}
int max_dsatur = -1;
for (int i = 0; i < n; i++) {
if (degree(i) > degree(max_dsatur)) {
max_dsatur = i;
}
}
color[max_dsatur] = 0;
int count = 1;
while (count < n) {
int u = find_max_dsatur();
int available[MAXN], k = 0;
for (int i = 0; i < n; i++) {
if (graph[u][i] == 1 && color[i] != -1) {
colored[color[i]]++;
}
}
for (int i = 0; i < count; i++) {
if (colored[i] == 0) {
available[k++] = i;
}
}
if (k == 0) {
color[u] = count++;
} else {
int idx = available[0];
for (int i = 1; i < k; i++) {
if (degree(available[i]) > degree(idx)) {
idx = available[i];
}
}
color[u] = idx;
}
for (int i = 0; i < n; i++) {
if (graph[u][i] == 1 && color[i] != -1) {
colored[color[i]]--;
}
}
}
}
void output() {
cout << "Total colors: " << *max_element(color, color + n) + 1 << endl;
for (int i = 0; i < n; i++) {
cout << "Node " << i << " - Color: " << color[i] + 1 << endl;
}
}
int main() {
input();
dsatur();
output();
return 0;
}
import numpy as np
def input_data():
with open("colorx.txt", "r") as f:
n = int(f.readline())
graph = []
for i in range(n):
graph.append(list(map(int, f.readline().split())))
return n, np.array(graph)
def degree(graph, u):
return np.sum(graph[u,:])
def find_max_dsatur(graph, color, colored, saturation):
max_saturation = -1
max_dsatur = -1
for i in range(graph.shape[0]):
if color[i] == -1:
saturation[i] = 0
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] += 1
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] == -1:
saturation[i] += 1
if saturation[i] > max_saturation or (saturation[i] == max_saturation and degree(graph, i) > degree(graph, max_dsatur)):
max_saturation = saturation[i]
max_dsatur = i
for j in range(graph.shape[0]):
if graph[i,j] == 1 and color[j] != -1:
colored[int(color[j])] -= 1
return max_dsatur
def dsatur(graph):
color = np.full(graph.shape[0], -1)
colored = np.zeros(graph.shape[0], dtype=int)
saturation = np.zeros(graph.shape[0], dtype=int)
max_dsatur = np.argmax([degree(graph, i) for i in range(graph.shape[0])])
color[max_dsatur] = 0
count = 1
while count < graph.shape[0]:
u = find_max_dsatur(graph, color, colored, saturation)
available = np.where(colored == 0)[0]
k = len(available)
if k == 0:
color[u] = count
count += 1
else:
idx = available[0]
for i in range(1, k):
if degree(graph, available[i]) > degree(graph, idx):
idx = available[i]
color[u] = idx
colored[color[u]] = 1
return color
def output_data(color):
print("Total colors:", np.amax(color) + 1)
for i, c in enumerate(color):
print("Node", i, "-", "Color:", c + 1)
if __name__ == "__main__":
n, graph = input_data()
color = dsatur(graph)
output_data(color)
Nó sử dụng thư viện NumPy để tối ưu hóa tính toán. Vì lý do đó, đoạn mã này có thể chạy nhanh hơn so với đoạn mã C++.
def dsatur(graph):
color = np.full(graph.shape[0], -1)
colored = np.zeros(graph.shape[0], dtype=int)
saturation = np.zeros(graph.shape[0], dtype=int)
max_dsatur = np.argmax([degree(graph, i) for i in range(graph.shape[0])])
color[max_dsatur] = 0
count = 1
while count < graph.shape[0]:
u = find_max_dsatur(graph, color, colored, saturation)
available = np.where(colored == 0)[0]
k = len(available)
if k == 0:
color[u] = count
count += 1
else:
idx = available[0]
for i in range(1, k):
if degree(graph, available[i]) > degree(graph, idx):
idx = available[i]
color[u] = idx
colored[color[u]] = 1
return color
def output_data(color):
print(“Total colors:”, np.amax(color) + 1)
for i, c in enumerate(color):
print(“Node”, i, “-”, “Color:”, c + 1)
if name == “main”:
n, graph = input_data()
color = dsatur(graph)
output_data(color)
Các ký tự ", ' và “, ” là khác nhau. Bạn phải sử dụng ký tự ", không nên dùng ký tự “,” và ”.
Lưu ý rằng bạn nên sử dụng cách đặt nằm trong chuẩn của Python, dùng to