有人可以帮助我解决以下代码的每个部分的时间复杂性,包括for循环和if循环以及所有这些。
public class GaleShapley {
private int N, engagedCount;
private int[][] menPref;
private int[][] womenPref;
private int[] men;
private int[] women;
private int[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(int[] m, int[] w, int[][] mp, int[][] wp) {
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new int[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches() {
while (engagedCount < N) {
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++) {
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == 0) {
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
} else {
int currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index)) {
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(int curPartner, int newPartner, int index) {
for (int i = 0; i < N; i++) {
if (womenPref[index][i] == newPartner)
return true;
if (womenPref[index][i] == curPartner)
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(int str) {
for (int i = 0; i < N; i++)
if (men[i] == str)
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(int str) {
for (int i = 0; i < N; i++)
if (women[i] == str)
return i;
return -1;
}
/** print couples **/
public void printCouples() {
System.out.println("Couples are : ");
for (int i = 0; i < N; i++) {
System.out.println(women[i] + " " + womenPartner[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
int[] m = { 1, 2, 3, 4, 5 };
/** list of women **/
int[] w = { 1, 2, 3, 4, 5 };
/** men preference **/
int[][] mp = { { 2, 4, 1, 3, 5 }, { 3, 1, 4, 2, 5 }, { 2, 3, 1, 4, 5 },
{ 4, 1, 3, 2, 5 }, { 2, 1, 4, 3, 5 } };
/** women preference **/
int[][] wp = { { 2, 1, 4, 3 }, { 4, 3, 1, 2 }, { 1, 4, 3, 2 },
{ 2, 1, 4, 3 }, { 2, 1, 4, 3 } };
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
我假设时间复杂度是O(n ^ 2)。需要有人确认一样。
答案 0 :(得分:0)
你的功能以while
循环(从0到N)开始。
在此循环中,您有2个for
循环(从0到N)。
在第二个for
循环中,您调用方法morePreference
,menIndexOf
和womenIndexOf
。
这些方法中的每一个都包含一个for
循环(从0到N)。
因此,您的算法的复杂性为O(N^3)