- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在寻找用于 JavaScript 或类似算法的 Blossom 算法的实现。
我有一对
A - B
A - C
B - D
我需要选对,假设每个字母只能在输出中结束一次。在上述情况下,正确的结果是
A - C
B - D
因为 A、B、C 和 D 最终都会出现在结果中。错误的结果是
A - B
这会将 C 和 D 排除在外。
最佳答案
当然可以,为什么不呢?
/*
Edmonds's maximum matching algorithm
Complexity: O(v^3)
Written by Felipe Lopes de Freitas
Adapted to JavaScript from C++ (http://pastebin.com/NQwxv32y) by גלעד ברקן
*/
var MAX = 100,
undef = -2,
empty = -1,
noEdge = 0,
unmatched = 1,
matched = 2,
forward = 0,
reverse = 0;
//Labels are the key to this implementation of the algorithm.
function Label(){ //An even label in a vertex means there's an alternating path
this.even = undefined; //of even length starting from the root node that ends on the
this.odd = new Array(2); //vertex. To find this path, the backtrace() function is called,
}; //constructing the path by following the content of the labels.
//Odd labels are similar, the only difference is that base nodes
//of blossoms inside other blossoms may have two. More on this later.
function elem(){ //This is the element of the queue of labels to be analyzed by
this.vertex = undefined;
this.type = undefined; //the augmentMatching() procedure. Each element contains the vertex
}; //where the label is and its type, odd or even.
var g = new Array(MAX); //The graph, as an adjacency matrix.
for (var i=0; i<MAX; i++){
g[i] = new Array(MAX);
}
//blossom[i] contains the base node of the blossom the vertex i
var blossom = new Array(MAX); //is in. This, together with labels eliminates the need to
//contract the graph.
//The path arrays are where the backtrace() routine will
var path = new Array(2);
for (var i=0; i<2; i++){
path[i] = new Array(MAX);
}
var endPath = new Array(2); //store the paths it finds. Only two paths need to be
//stored. endPath[p] denotes the end of path[p].
var match = new Array(MAX); //An array of flags. match[i] stores if vertex i is in the matching.
//label[i] contains the label assigned to vertex i. It may be undefined,
var label = new Array(MAX); //empty (meaning the node is a root) and a node might have even and odd
//labels at the same time, which is the case for nonbase nodes of blossoms
for (var i=0; i<MAX; i++){
label[i] = new Label();
}
var queue = new Array(2*MAX); //The queue is necessary for efficiently scanning all labels.
var queueFront,queueBack; //A label is enqueued when assigned and dequeued after scanned.
for (var i=0; i<2*MAX; i++){
queue[i] = new elem();
}
function initGraph(n){
for (var i=0; i<n; i++)
for (var j=0; j<n; j++) g[i][j]=noEdge;
}
function readGraph(){
var n = graph.n,
e = graph.e;
//int n,e,a,b;
//scanf(" %d %d",&n,&e); //The graph is read and its edges are unmatched by default.
initGraph(n); //Since C++ arrays are 0..n-1 and input 1..n , subtractions
for (var i=0; i<e; i++){ //are made for better memory usage.
//scanf(" %d %d",&a,&b);
var a = graph[i][0],
b = graph[i][1];
if (a!=b)
g[a-1][b-1]=g[b-1][a-1]=unmatched;
}
return n;
}
function initAlg(n){ //Initializes all data structures for the augmentMatching()
queueFront=queueBack=0; //function begin. At the start, all labels are undefined,
for (var i=0; i<n; i++){ //the queue is empty and a node alone is its own blossom.
blossom[i]=i;
label[i].even=label[i].odd[0]=label[i].odd[1]=undef;
}
}
function backtrace (vert, pathNum, stop, parity, direction){
if (vert==stop) return; //pathNum is the number of the path to store
else if (parity==0){ //vert and parity determine the label to be read.
if (direction==reverse){
backtrace(label[vert].even,pathNum,stop,(parity+1)%2,reverse);
path[pathNum][endPath[pathNum]++]=vert;
} //forward means the vertices called first enter
else if (direction==forward){ //the path first, reverse is the opposite.
path[pathNum][endPath[pathNum]++]=vert;
backtrace(label[vert].even,pathNum,stop,(parity+1)%2,forward);
}
}
/*
stop is the stopping condition for the recursion.
Recursion is necessary because of the possible dual odd labels.
having empty at stop means the recursion will only stop after
the whole tree has been climbed. If assigned to a vertex, it'll stop
once it's reached.
*/
else if (parity==1 && label[vert].odd[1]==undef){
if (direction==reverse){
backtrace(label[vert].odd[0],pathNum,stop,(parity+1)%2,reverse);
path[pathNum][endPath[pathNum]++]=vert;
}
else if (direction==forward){
path[pathNum][endPath[pathNum]++]=vert;
backtrace(label[vert].odd[0],pathNum,stop,(parity+1)%2,forward);
}
}
/*
Dual odd labels are interpreted as follows:
There exists an odd length alternating path starting from the root to this
vertex. To find this path, backtrace from odd[0] to the top of the tree and
from odd[1] to the vertex itself. This, put in the right order, will
constitute said path.
*/
else if (parity==1 && label[vert].odd[1]!=undef){
if (direction==reverse){
backtrace(label[vert].odd[0],pathNum,empty,(parity+1)%2,reverse);
backtrace(label[vert].odd[1],pathNum,vert,(parity+1)%2,forward);
path[pathNum][endPath[pathNum]++]=vert;
}
else if (direction==forward){
backtrace(label[vert].odd[1],pathNum,vert,(parity+1)%2,reverse);
backtrace(label[vert].odd[0],pathNum,empty,(parity+1)%2,forward);
path[pathNum][endPath[pathNum]++]=vert;
}
}
}
function enqueue (vert, t){
var tmp = new elem(); //Enqueues labels for scanning.
tmp.vertex=vert; //No label that's dequeued during the execution
tmp.type=t; //of augmentMatching() goes back to the queue.
queue[queueBack++]=tmp; //Thus, circular arrays are unnecessary.
}
function newBlossom (a, b){ //newBlossom() will be called after the paths are evaluated.
var i,base,innerBlossom,innerBase;
for (i=0; path[0][i]==path[1][i]; i++); //Find the lowest common ancestor of a and b
i--; //it will be used to represent the blossom.
base=blossom[path[0][i]]; //Unless it's already contained in another...
//In this case, all will be put in the older one.
for (var j=i; j<endPath[0]; j++) blossom[path[0][j]]=base;
for (var j=i+1; j<endPath[1]; j++) blossom[path[1][j]]=base; //Set all nodes to this
for (var p=0; p<2; p++){ //new blossom.
for (var j=i+1; j<endPath[p]-1; j++){
if (label[path[p][j]].even==undef){ //Now, new labels will be applied
label[path[p][j]].even=path[p][j+1]; //to indicate the existence of even
enqueue(path[p][j],0); //and odd length paths.
}
else if (label[path[p][j]].odd[0]==undef && label[path[p][j+1]].even==undef){
label[path[p][j]].odd[0]=path[p][j+1];
enqueue(path[p][j],1); //Labels will only be put if the vertex
} //doesn't have one.
else if (label[path[p][j]].odd[0]==undef && label[path[p][j+1]].even!=undef){
/*
If a vertex doesn't have an odd label, but the next one in the path
has an even label, it means that the current vertex is the base node
of a previous blossom and the next one is contained within it.
The standard labeling procedure will fail in this case. This is fixed
by going to the last node in the path inside this inner blossom and using
it to apply the dual label.
Refer to backtrace() to know how the path will be built.
*/
innerBlossom=blossom[path[p][j]];
innerBase=j;
for (; blossom[j]==innerBlossom && j<endPath[p]-1; j++);
j--;
label[path[p][innerBase]].odd[0]=path[p][j+1];
label[path[p][innerBase]].odd[1]=path[p][j];
enqueue(path[p][innerBase],1);
}
}
}
if (g[a][b]==unmatched){ //All nodes have received labels, except
if (label[a].odd[0]==undef){ //the ones that called the function in
label[a].odd[0]=b; //the first place. It's possible to
enqueue(a,1); //find out how to label them by
} //analyzing if they're in the matching.
if (label[b].odd[0]==undef){
label[b].odd[0]=a;
enqueue(b,1);
}
}
else if (g[a][b]==matched){
if (label[a].even==undef){
label[a].even=b;
enqueue(a,0);
}
if (label[b].even==undef){
label[b].even=a;
enqueue(b,0);
}
}
}
function augmentPath (){ //An augmenting path has been found in the matching
var a,b; //and is contained in the path arrays.
for (var p=0; p<2; p++){
for (var i=0; i<endPath[p]-1; i++){
a=path[p][i]; //Because of labeling, this path is already
b=path[p][i+1]; //lifted and can be augmented by simple
if (g[a][b]==unmatched) //changing of the matching status.
g[a][b]=g[b][a]=matched;
else if (g[a][b]==matched)
g[a][b]=g[b][a]=unmatched;
}
}
a=path[0][endPath[0]-1];
b=path[1][endPath[1]-1];
if (g[a][b]==unmatched) g[a][b]=g[b][a]=matched;
else if (g[a][b]==matched) g[a][b]=g[b][a]=unmatched;
//After this, a and b are included in the matching.
match[path[0][0]]=match[path[1][0]]=true;
}
function augmentMatching (n){ //The main analyzing function, with the
var node,nodeLabel; //goal of finding augmenting paths or
initAlg(n); //concluding that the matching is maximum.
for (var i=0; i<n; i++) if (!match[i]){
label[i].even=empty;
enqueue(i,0); //Initialize the queue with the exposed vertices,
} //making them the roots in the forest.
while (queueFront<queueBack){
node=queue[queueFront].vertex;
nodeLabel=queue[queueFront].type;
if (nodeLabel==0){
for (var i=0; i<n; i++) if (g[node][i]==unmatched){
if (blossom[node]==blossom[i]);
//Do nothing. Edges inside the same blossom have no meaning.
else if (label[i].even!=undef){
/*
The tree has reached a vertex with a label.
The parity of this label indicates that an odd length
alternating path has been found. If this path is between
roots, we have an augmenting path, else there's an
alternating cycle, a blossom.
*/
endPath[0]=endPath[1]=0;
backtrace(node,0,empty,0,reverse);
backtrace(i,1,empty,0,reverse);
//Call the backtracing function to find out.
if (path[0][0]==path[1][0]) newBlossom(node,i);
/*
If the same root node is reached, a blossom was found.
Start the labelling procedure to create pseudo-contraction.
*/
else {
augmentPath();
return true;
/*
If the roots are different, we have an augmenting path.
Improve the matching by augmenting this path.
Now some labels might make no sense, stop the function,
returning that it was successful in improving.
*/
}
}
else if (label[i].even==undef && label[i].odd[0]==undef){
//If an unseen vertex is found, report the existing path
//by labeling it accordingly.
label[i].odd[0]=node;
enqueue(i,1);
}
}
}
else if (nodeLabel==1){ //Similar to above.
for (var i=0; i<n; i++) if (g[node][i]==matched){
if (blossom[node]==blossom[i]);
else if (label[i].odd[0]!=undef){
endPath[0]=endPath[1]=0;
backtrace(node,0,empty,1,reverse);
backtrace(i,1,empty,1,reverse);
if (path[0][0]==path[1][0]) newBlossom(node,i);
else {
augmentPath();
return true;
}
}
else if (label[i].even==undef && label[i].odd[0]==undef){
label[i].even=node;
enqueue(i,0);
}
}
}
/*
The scanning of this label is complete, dequeue it and
keep going to the next one.
*/
queueFront++;
}
/*
If the function reaches this point, the queue is empty, all
labels have been scanned. The algorithm couldn't find an augmenting
path. Therefore, it concludes the matching is maximum.
*/
return false;
}
function findMaximumMatching (n){
//Initialize it with the empty matching.
for (var i=0; i<n; i++) match[i]=false;
//Run augmentMatching(), it'll keep improving the matching.
//Eventually, it will no longer find a path and break the loop,
//at this point, the current matching is maximum.
while (augmentMatching(n));
}
function main(){
var n;
n=readGraph();
findMaximumMatching(n);
for (var i=0; i<n; i++){
for (var j=i+1; j<n; j++) if (g[i][j]==matched)
console.log(i+1,j+1);
}
return 0;
}
输出:
var graph = [[1,2]
,[1,3]
,[2,4]];
graph["n"] = 4;
graph["e"] = 3;
main()
1 3
2 4
关于javascript - Javascript 中的匹配算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25706201/
我有一个 html 格式的表单: 我需要得到 JavaScript在value input 字段执行,但只能通过表单的 submit .原因是页面是一个模板所以我不控制它(不能有
我管理的论坛是托管软件,因此我无法访问源代码,我只能向页面添加 JavaScript 来实现我需要完成的任务。 我正在尝试用超链接替换所有页面上某些文本关键字的第一个实例。我还根据国家/地区代码对这些
我正在使用 JS 打开新页面并将 HTML 代码写入其中,但是当我尝试使用 document.write() 在新页面中编写 JS 时功能不起作用。显然,一旦看到 ,主 JS 就会关闭。用于即将打开的
提问不是为了解决问题,提问是为了更好地理解系统 专家!我知道每当你将 javascript 代码输入 javascript 引擎时,它会立即由 javascript 引擎执行。由于没有看过Engi
我在一个文件夹中有两个 javascript 文件。我想将一个变量的 javascript 文件传递到另一个。我应该使用什么程序? 最佳答案 window.postMessage用于跨文档消息。使
我有一个练习,我需要输入两个输入并检查它们是否都等于一个。 如果是 console.log 正则 console.log false 我试过这样的事情: function isPositive(fir
我正在做一个Web应用程序,计划允许其他网站(客户端)在其页面上嵌入以下javascript: 我的网络应用程序位于 http://example.org 。 我不能假设客户端网站的页面有 JQue
目前我正在使用三个外部 JS 文件。 我喜欢将所有三个 JS 文件合而为一。 尽一切可能。我创建 aio.js 并在 aio.js 中 src="https://code.jquery.com/
我有例如像这样的数组: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = {
所以我正在制作一个 Chrome 扩展,它使用我制作的一些 TamperMonkey 脚本。我想要一个“主”javascript 文件,您可以在其中包含并执行其他脚本。我很擅长使用以下行将其他 jav
我有 A、B html 和 A、B javascript 文件。 并且,如何将 A JavaScript 中使用的全局变量直接移动到 B JavaScript 中? 示例 JavaScript) va
我需要将以下整个代码放入名为 activate.js 的 JavaScript 中。你能告诉我怎么做吗? var int = new int({ seconds: 30, mark
我已经为我的 .net Web 应用程序创建了母版页 EXAMPLE1.Master。他们的 I 将值存储在 JavaScript 变量中。我想在另一个 JS 文件中检索该变量。 示例1.大师:-
是否有任何库可以用来转换这样的代码: function () { var a = 1; } 像这样的代码: function () { var a = 1; } 在我的浏览器中。因为我在 Gi
我收到语法缺失 ) 错误 $(document).ready(function changeText() { var p = document.getElementById('bidp
我正在制作进度条。它有一个标签。我想调整某个脚本完成的标签。在找到可能的解决方案的一些答案后,我想出了以下脚本。第一个启动并按预期工作。然而,第二个却没有。它出什么问题了?代码如下: HTML:
这里有一个很简单的问题,我简单的头脑无法回答:为什么我在外部库中加载时,下面的匿名和onload函数没有运行?我错过了一些非常非常基本的东西。 Library.js 只有一行:console.log(
我知道 javascript 是一种客户端语言,但如果实际代码中嵌入的 javascript 代码以某种方式与在控制台上运行的代码不同,我会尝试找到答案。让我用一个例子来解释它: 我想创建一个像 Mi
我如何将这个内联 javascript 更改为 Unobtrusive JavaScript? 谢谢! 感谢您的回答,但它不起作用。我的代码是: PHP js文件 document.getElem
我正在寻找将简单的 JavaScript 对象“转储”到动态生成的 JavaScript 源代码中的最优雅的方法。 目的:假设我们有 node.js 服务器生成 HTML。我们在服务器端有一个对象x。
我是一名优秀的程序员,十分优秀!