[英]All possible array combinations (parallel programming) - Optimal Graph Colouring
我再次進行最佳圖形着色的工作,因此,我需要為圖形生成所有可能的顏色組合(數組代表每個節點的顏色)。 正如您在以下問題中所看到的,我在這里得到了很多幫助:
現在,我的代碼是:
void generatearray( int array[], int array_size, int idx = 0, int fixed = 0 )
{
int i;
if ( idx == array_size )
{
putchar('\n');
for( i = 0; i < array_size; i++ ) printf( "%i ", array[i] );
} else {
for( i = 0; i <= 3; i++ )
{
if ( fixed == i )
{
fixed++;
array[idx] = i;
return generatearray( array, array_size, idx + 1, fixed );
}
array[idx] = i;
generatearray( array, array_size, idx + 1, fixed );
}
}
}
int arr[3];
generatearray( arr, 3 );
在這種情況下,輸出為:
0 0 0
0 0 1
0 1 0
0 1 1
0 1 2
如果0表示藍色,而2表示紅色,則在Graph着色中,紅色-紅色-紅色與藍色-藍色-藍色相同。 那就是我的代碼所做的:它為圖形生成所有可能的不同顏色組合。
現在我需要改進代碼,但是我什么也沒想到。 我希望它僅生成具有給定顏色數的數組,因為我使用的是pthreads,並且我希望每個線程都可以處理具有多種顏色的圖形。
例如:使用2種顏色,輸出將是:
0 0 1
0 1 0
0 1 1
並具有3種顏色:
1 2 3
我不需要它來創建顏色比設置的顏色少的數組,因為還有其他線程在執行此操作。
你們中的任何人都可以幫助我編寫代碼嗎? 抱歉,如果我在任何時候都沒有明確表示自己。
因此,您需要系統地枚舉所有從圖的頂點集V (#V = n)
到代表k
種不同顏色的k
元素的集合,以及將圖限制為索引最小的頂點的附加約束與相同顏色關聯的所有其他頂點之間,必須嚴格是單調的(因為您對各個顏色的標識不感興趣)。
讓我們假設顏色的數量是固定的。 首先選擇顏色代表的最小索引i_1, ..., i_k
。 根據定義, i_1 < ... < i_k
。 對於任何剩余頂點v
, i_j < v < i_(j+1)
,其顏色可以從{ 1, ..., j }
自由選擇。
這可以通過以下代碼實現:
/*
* sample values
* K ist to be substituted with the number of colors to use and thus in actual usage scenarios will be a parameter of thread instantiation
*/
const K = 4;
const N = 10;
void
next_pattern ( int *out, int set_up_to, int *mins, int mins_seen ) {
int i;
int choice;
/* in-place updating: only elements 1..set_up_to are valid */
if (set_up_to < N) {
if (set_up_to + 1 == mins[mins_seen+1]) {
out[set_up_to + 1] = mins_seen+1;
next_pattern ( out, set_up_to + 1, mins, mins_seen+1 );
}
else {
for ( choice = 1; choice <= mins_seen; choice++ ) {
out[set_up_to + 1] = choice;
next_pattern ( out, set_up_to + 1, mins, mins_seen );
}
}
}
else {
/* coloring complete */
printf("[");
for (i=1; i <= N; i++) {
printf(" %u ", out[i]);
}
printf("];\n");
}
} /* next_pattern */
void
next_mindist ( int *mins, int issued, int *out ) {
int lo;
/* in-place updating: only elements 1..issued are valid */
if (issued < K) {
for ( lo = mins[issued] + 1; lo < N - issued; lo++ ) {
mins[issued+1] = lo;
next_mindist ( mins, issued+1, out );
}
}
else {
// min mapping complete
next_pattern ( out, 0, mins, 0 );
}
} /* next_mindist */
void main ( char **argv, int *argc ) {
/* in-place arrays
* mins: minimum vertex index of color <index>
* out: current mapping vertex -> color (mostly partial during processing)
*/
int *mins = (int *) calloc ( sizeof(int), K + 2 ); /* supporting indices 1 .. K and upper guard to avoid conditional statements */
int *out = (int *) calloc ( sizeof(int), N + 1 ); /* supporting indices 1 .. N */
next_mindist ( mins, 0, out );
}
注意:上面的代碼確實可以編譯和運行,其結果似乎是正確的。 當然,其遠端形式已被正式驗證... ;-)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.