如何确定通过给定标准的子组的存在?

时间:2015-05-03 23:33:21

标签: c gcc c99 backtracking recursive-backtracking

作为家庭作业的一部分,我需要编写一个函数,如果给定的数组中存在“好”子组,则返回true。 “好子组”是一个子组,每个组成员中特定字段(整数)的总和大于给定目标(特别是数组原始长度的一半),并且每个成员都是集团与该集团的所有其他成员“相处”。 如果class ThreadedMatcher extends Thread { private $query; private $param; public $result; public $id; public function __construct($params) { $this->query = $params['query']; $this->param = $params['param']; $this->id= $params['id']; } public function run() { /* do some stuff*/ echo ($this->query); echo ($this->param); $this->result = rand(100, 200); } } $Pay_Load=array( array('id'=>$id,'query'=>$query1,'param'=>$param1), array('id'=>$id,'query'=>$query2,'param'=>$param2), /*... can be hundreds...just an example...*/ ) $Nb_of_Cpus=4; $Nb_of_threads=$Nb_of_Cpus*2; $Batch_Works=array_chunk($Pay_Load,$Nb_of_threads); $threads = []; $results = array(); foreach ($Batch_Works as $batch) { foreach ($batch as $key => $params) { $threads[$key] = new ThreadedMatcher($params); $threads[$key]->start(); } foreach ($batch as $key => $params) { $threads[$key]->join(); $returned_result=$threads[$key]->result; $returned_id=$threads[$key]->id; $result=array($returned_id=>$returned_result); array_push($results, result); } } /* all returned results are now in the same array */ /* with the original Payload id as an example here */ var_dump($results); $results =( 1=>103, 2=>234, 3=>345, 4=>123) ,2名成员“相处”。这是我到目前为止所尝试的,但似乎不起作用:

(abs(m1->f1 - m2->f1) + abs(m1->f2 - m2-f2)) <= given_hatred

我还要提到的是,Member是一个抽象数据类型,它实现了以//-----helpers----- //checks if the new candiate member likes the others static bool fits(Member* a,int curr,int chosen[],double get_along) { for(int i=0; i<curr;i++) { if(chosen[i]==1) { int iA=memberGetGAFactorA(a[i]); int iB=memberGetGAFactorB(a[i]); int currA=memberGetGAFactorA(a[curr]); int currB=memberGetGAFactorB(a[curr]); if(abs_f(iA-currA)+abs_f(iB-currB)>get_along) return false; } } return true; } //backtracking static bool subsum(Members* a, int n, int size, int sum, int chosen[], int curr, double get_allong) { if(sum > size) return true; if(n <= 0) return false; if(fits(arr,curr,chosen,get_along)) { chosen[curr]=1; int inSum = sum+memberGetFieldNum(a[0]); if (subsum(a+1, n-1, size - memberGetFieldNum(a[0]), inSum, chosen, curr + 1, get_along)) return true; } chosen [curr] = 0; return subsum(a+1,n-1,size,sum,chosen,curr+1,get_along); } //------the wanted function------- bool subGroupExists(Members* array,length, double get_along) { int* chosen = calloc(length,sizeof(int)); bool res = subsum(array,length,length/2,0,chosen,0,get_along); free(chosen); return res; } 开头的所有函数,并且工作正常(经过测试)。

编辑: 我发现了一种解决方法,我很快就会发布,但我对其他解决方案非常感兴趣,所以请随意:)

0 个答案:

没有答案