【发布时间】:2016-11-05 14:10:21
【问题描述】:
找到n choose 2 与2 <= n <= 100000 的所有组合的最有效方法是什么?
例如,5 choose 2 是
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
这是我迄今为止测试最坏情况的方法:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ITEMS 100000
void combinations(int[], int);
long long count = 0;
int main(void) {
int *arr = (int*) calloc(MAX_ITEMS, sizeof(int));
if (!arr) {
printf("Error allocating memory.");
exit(1);
}
int i, n = MAX_ITEMS;
for (i = 0; i < MAX_ITEMS; i++) {
arr[i] = i + 1;
}
clock_t start, diff;
int msec;
start = clock();
combinations(arr, n);
diff = clock() - start;
msec = diff * 1000 / CLOCKS_PER_SEC;
printf("\n\nTime taken %d seconds %d milliseconds", msec / 1000, msec % 1000);
printf("\n\nPairs = %lld\n", count);
return 0;
}
void combinations(int arr[], int n) {
int i, j, comb1, comb2, end = n - 1;
for (i = 0; i < end; i++) {
for (j = i + 1; j < n; j++) {
// simulate doing something with data at these indices
comb1 = arr[i];
comb2 = arr[j];
// printf("%d %d\n", arr[i], arr[j]);
count++;
}
}
}
输出
Time taken 28 seconds 799 milliseconds
Pairs = 4999950000
我可能弄错了,但时间复杂度是 O(n^2)。
是否有更有效的算法来处理最坏的情况?
【问题讨论】:
-
你应该看看这篇文章 - stackoverflow.com/questions/127704/…
-
(n * (n-1)) / 2怎么样?还是您在实际配对之后?如果是这样,O(n^2) 是你能做的最好的。 -
@aioobe 是的,我需要实际的配对。
-
@turion 如果您需要打印/存储所有实际对, (n*(n-1))/2 = O(n^2) 是最好的,因为它是准确的你需要的 I/O 时间,有意义吗?
标签: c algorithm performance combinatorics