当前位置:网站首页>June 12, 2022: if there are n*n pieces in an n*n square chessboard, each grid can have exactly one piece. But now some pieces are gathered on a grid, such as 2030100300. The above two-dimensional arra
June 12, 2022: if there are n*n pieces in an n*n square chessboard, each grid can have exactly one piece. But now some pieces are gathered on a grid, such as 2030100300. The above two-dimensional arra
2022-06-13 06:51:00 【Fuda scaffold constructor's daily question】
2022-06-12: stay NN On a square chessboard , Yes NN A chess piece , Then each grid can have exactly one chess piece .
But now some pieces are gathered on a grid , such as :
2 0 3
0 1 0
3 0 0
The above two-dimensional array represents , altogether 3*3 Lattice ,
But some grids have 2 A chess piece 、 Some have 3 individual 、 Some have 1 individual 、 Some don't ,
Please move the chess pieces , Let each square have a piece ,
Each piece can be played 、 Next 、 Left 、 Move right , Every move counts 1 The price of .
Return the minimum cost .
From Microsoft .
answer 2022-06-12:
km Algorithm , Negative distance .
The code to use rust To write . The code is as follows :
use rand::Rng;
fn main() {
let len: i32 = 4;
let test_time: i32 = 1000;
println!(" Beginning of the test ");
for _ in 0..test_time {
let mut graph = random_valid_matrix(len);
let ans1 = min_distance1(&mut graph);
let ans2 = min_distance2(&mut graph);
if ans1 != ans2 {
println!(" Something went wrong !");
println!("ans1 = {}", ans1);
println!("ans2 = {}", ans2);
println!("===============");
}
}
println!(" End of test ");
}
// Violent solution
// As logarithm
fn min_distance1(map: &mut Vec<Vec<i32>>) -> i32 {
let mut n = 0;
let mut m = 0;
for i in 0..map.len() as i32 {
for j in 0..map[0].len() as i32 {
n += get_max(0, map[i as usize][j as usize] - 1);
m += if map[i as usize][j as usize] == 0 {
1
} else {
0
};
}
}
if n != m || n == 0 {
return 0;
}
let mut nodes: Vec<Vec<i32>> = vec![];
for i in 0..n {
nodes.push(vec![]);
for _ in 0..2 {
nodes[i as usize].push(0);
}
}
let mut space: Vec<Vec<i32>> = vec![];
for i in 0..m {
space.push(vec![]);
for _ in 0..2 {
space[i as usize].push(0);
}
}
n = 0;
m = 0;
for i in 0..map.len() as i32 {
for j in 0..map[0].len() as i32 {
for _k in 2..map[i as usize][j as usize] {
nodes[n as usize][0] = i;
nodes[n as usize][1] = j;
n += 1;
}
if map[i as usize][j as usize] == 0 {
space[m as usize][0] = i;
space[m as usize][1] = j;
m += 1;
}
}
}
return process1(&mut nodes, 0, &mut space);
}
fn process1(nodes: &mut Vec<Vec<i32>>, index: i32, space: &mut Vec<Vec<i32>>) -> i32 {
let mut ans = 0;
if index == nodes.len() as i32 {
for i in 0..nodes.len() as i32 {
ans += distance(&mut nodes[i as usize], &mut space[i as usize]);
}
} else {
ans = 2147483647;
for i in index..nodes.len() as i32 {
swap(nodes, index, i);
ans = get_min(ans, process1(nodes, index + 1, space));
swap(nodes, index, i);
}
}
return ans;
}
fn swap(nodes: &mut Vec<Vec<i32>>, i: i32, j: i32) {
let tmp = nodes[i as usize].clone();
nodes[i as usize] = nodes[j as usize].clone();
nodes[j as usize] = tmp.clone();
}
fn distance(a: &mut Vec<i32>, b: &mut Vec<i32>) -> i32 {
return abs(a[0] - b[0]) + abs(a[1] - b[1]);
}
fn abs(a: i32) -> i32 {
if a < 0 {
-a
} else {
a
}
}
// Formal approach
// KM Algorithm
fn min_distance2(map: &mut Vec<Vec<i32>>) -> i32 {
let mut n = 0;
let mut m = 0;
for i in 0..map.len() as i32 {
for j in 0..map[0].len() as i32 {
n += get_max(0, map[i as usize][j as usize] - 1);
m += if map[i as usize][j as usize] == 0 {
1
} else {
0
};
}
}
if n != m || n == 0 {
return 0;
}
let mut nodes: Vec<Vec<i32>> = vec![];
for i in 0..n {
nodes.push(vec![]);
for _ in 0..2 {
nodes[i as usize].push(0);
}
}
let mut space: Vec<Vec<i32>> = vec![];
for i in 0..m {
space.push(vec![]);
for _ in 0..2 {
space[i as usize].push(0);
}
}
n = 0;
m = 0;
for i in 0..map.len() as i32 {
for j in 0..map[0].len() as i32 {
for _k in 2..=map[i as usize][j as usize] {
nodes[n as usize][0] = i;
nodes[n as usize][1] = j;
n += 1;
}
if map[i as usize][j as usize] == 0 {
space[m as usize][0] = i;
space[m as usize][1] = j;
m += 1;
}
}
}
let mut graph: Vec<Vec<i32>> = vec![];
for i in 0..n {
graph.push(vec![]);
for _ in 0..n {
graph[i as usize].push(0);
}
}
for i in 0..n {
for j in 0..n {
graph[i as usize][j as usize] =
-distance(&mut nodes[i as usize], &mut space[j as usize]);
}
}
return -km(&mut graph);
}
fn get_max<T: Clone + Copy + std::cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
fn get_min<T: Clone + Copy + std::cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
fn km(graph: &mut Vec<Vec<i32>>) -> i32 {
let nn = graph.len() as i32;
let mut match0: Vec<i32> = vec![];
let mut lx: Vec<i32> = vec![];
let mut ly: Vec<i32> = vec![];
// dfs In the process , Touched points !
let mut x: Vec<bool> = vec![];
let mut y: Vec<bool> = vec![];
// Lowered expectations !
// Princess , Make a , Lower the expected value , Keep it to a minimum !
let mut slack: Vec<i32> = vec![];
let mut falsev: Vec<bool> = vec![];
for _ in 0..nn {
match0.push(0);
lx.push(0);
ly.push(0);
x.push(false);
y.push(false);
slack.push(0);
falsev.push(false);
}
let invalid = 2147483647;
for i in 0..nn {
match0[i as usize] = -1;
lx[i as usize] = -invalid;
for j in 0..nn {
lx[i as usize] = get_max(lx[i as usize], graph[i as usize][j as usize]);
}
ly[i as usize] = 0;
}
for from in 0..nn {
for i in 0..nn {
slack[i as usize] = invalid;
}
x = falsev.clone();
y = falsev.clone();
// dfs() : from prince , Can we not lower our expectations , The match is successful !
// can :dfs return true!
// You can't :dfs return false!
while !dfs(
from,
&mut x,
&mut y,
&mut lx,
&mut ly,
&mut match0,
&mut slack,
graph,
) {
// Just now dfs, failed !
// Need to get , Princess's slack Inside , The minimum value of the expected decrease !
let mut d = invalid;
for i in 0..nn {
if !y[i as usize] && slack[i as usize] < d {
d = slack[i as usize];
}
}
// Adjust the expectation according to the minimum expectation
for i in 0..nn {
if x[i as usize] {
lx[i as usize] = lx[i as usize] - d;
}
if y[i as usize] {
ly[i as usize] = ly[i as usize] + d;
}
}
x = falsev.clone();
y = falsev.clone();
// Then back while in , Try it again
}
}
let mut ans = 0;
for i in 0..nn {
ans += lx[i as usize] + ly[i as usize];
}
return ans;
}
// from, The current Prince
// x, Did the prince touch it
// y, Did the princess touch it
// lx, All the prince's expectations
// ly, All the princess's expectations
// match, All the princesses , Previous assignments , Men before !
// slack, Continuous , But the princess without permission , The minimum decrease
// map, offer , All the prince's offers to the princess
// return ,from Prince No , Do not lower expectations can match !
fn dfs(
from: i32,
x: &mut Vec<bool>,
y: &mut Vec<bool>,
lx: &mut Vec<i32>,
ly: &mut Vec<i32>,
match0: &mut Vec<i32>,
slack: &mut Vec<i32>,
map: &mut Vec<Vec<i32>>,
) -> bool {
let nn = map.len() as i32;
x[from as usize] = true;
for to in 0..nn {
if !y[to as usize] {
// Only No dfs The princess who passed , To try
let d = lx[from as usize] + ly[to as usize] - map[from as usize][to as usize];
if d != 0 {
// If the current road does not meet expectations , Update the princess's slack value
slack[to as usize] = get_min(slack[to as usize], d);
} else {
// If the current road meets expectations , Try to take it directly , Or grab and let the previous arrangement go upside down
y[to as usize] = true;
if match0[to as usize] == -1
|| dfs(match0[to as usize], x, y, lx, ly, match0, slack, map)
{
match0[to as usize] = from;
return true;
}
}
}
}
return false;
}
// In order to test
fn random_valid_matrix(len: i32) -> Vec<Vec<i32>> {
let mut graph: Vec<Vec<i32>> = vec![];
for i in 0..len {
graph.push(vec![]);
for _ in 0..len {
graph[i as usize].push(0);
}
}
let all = len * len;
for _i in 1..all {
graph[rand::thread_rng().gen_range(0, len) as usize]
[rand::thread_rng().gen_range(0, len) as usize] += 1;
}
return graph;
}
The results are as follows :

边栏推荐
- Common method of props changing value V-model sync
- Pngquant batch bat and parameter description
- Vue3 route cache component status and set transition animation
- YOLOv5解析 | 参数与性能指标
- How to use Wangyou DFM software for cold plate analysis
- package-lock. json
- DataGridView data export to excel (in case of small amount of data)
- 105. constructing binary trees from preorder and inorder traversal sequences
- 牙周炎问题调研(持续进行中)
- Soup side (8)
猜你喜欢

牙周炎问题调研(持续进行中)

数据在内存中的存储(C语言)

Notepad++ settings delete current line shortcut

Jinglianwen Technology: current situation and solutions of data annotation industry
![[virtual machine] VMware virtual machine occupies too much space. Solution](/img/3d/bca30c6e6f7fa8400a077ed0a29e16.png)
[virtual machine] VMware virtual machine occupies too much space. Solution

The new business outlet of beautiful Tiantian second mode will be popular in the Internet e-commerce market

How to seize the bonus of social e-commerce through brand play to achieve growth and profit?
![[SketchUp 2021] CAD file import and modeling in the sketch master (establish elevation model in the sketch master by using CAD drawings), and the sketch master exports 2D, 3D and elevation effects of](/img/de/d0620a43c47a06d815c21ecb41a117.png)
[SketchUp 2021] CAD file import and modeling in the sketch master (establish elevation model in the sketch master by using CAD drawings), and the sketch master exports 2D, 3D and elevation effects of

【微弱瞬态信号检测】混沌背景下微弱瞬态信号的SVM检测方法的matlab仿真

Common method of props changing value V-model sync
随机推荐
Analyzing server problems using jvisualvm
'ipconfig' is not an internal or external command, nor is it a runnable program or batch file.
Xiaomi's one-sided interview questions (self sorting answers)
Custom attribute acquisition of view in applet
Ijkplayer compilation process record
Machine learning notes - supervised learning memo list
上位机开发(固件下载软件之详细设计)
Array operations in JS
Intelligent entertainment has developed steadily, and jinglianwen technology provides data collection and labeling services
JS case Xiaomi second kill countdown New Year Countdown
Tidb implementation plan -- I
That is, after the negative impact of gcat advertising e-commerce, is there no stable advertising e-commerce platform?
Scrcpy development environment construction and source code reading
Project analysis of Taishan crowdfunding mode: why is Taishan crowdfunding mode so popular?
Detailed explanation of the player network data reading process of ijkplayer code walkthrough 2
ML之FE:Vintage曲线/Vintage分析的简介、计算逻辑、案例应用之详细攻略
杭州证券开户是安全的吗?
Introduction to applet layout
If the key in redis data is in Chinese
[system analysis and design] college student association management system