119 lines
2.8 KiB
Java
119 lines
2.8 KiB
Java
import java.util.*;
|
|
|
|
public class galeShapley {
|
|
|
|
static int N;
|
|
|
|
static int womanCharToIndex(char ch) {
|
|
return ch - 'W';
|
|
}
|
|
|
|
static int manCharToIndex(char ch) {
|
|
return ch - 'A';
|
|
}
|
|
|
|
static boolean prefers(int[][] womenPref, int w, int m, int m1) {
|
|
for (int i = 0; i < N; i++) {
|
|
if (womenPref[w][i] == m)
|
|
return true;
|
|
|
|
if (womenPref[w][i] == m1)
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static void galeShapley(int[][] womenPref, int[][] menPref) {
|
|
|
|
int[] womenPartner = new int[N];
|
|
boolean[] menFree = new boolean[N];
|
|
int[] nextProposal = new int[N];
|
|
|
|
Arrays.fill(womenPartner, -1);
|
|
Arrays.fill(menFree, true);
|
|
|
|
int freeCount = N;
|
|
|
|
while (freeCount > 0) {
|
|
|
|
int m = -1;
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
if (menFree[i] && nextProposal[i] < N) {
|
|
m = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (m == -1)
|
|
break;
|
|
|
|
int w = menPref[m][nextProposal[m]];
|
|
nextProposal[m]++;
|
|
|
|
if (womenPartner[w] == -1) {
|
|
womenPartner[w] = m;
|
|
menFree[m] = false;
|
|
freeCount--;
|
|
} else {
|
|
|
|
int m1 = womenPartner[w];
|
|
|
|
if (prefers(womenPref, w, m, m1)) {
|
|
womenPartner[w] = m;
|
|
menFree[m] = false;
|
|
menFree[m1] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
System.out.println("\nStable matching result:");
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
System.out.println(
|
|
"Woman " + (char)('W' + i) +
|
|
" is matched with Man " + (char)('A' + womenPartner[i])
|
|
);
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Scanner sc = new Scanner(System.in);
|
|
|
|
System.out.print("Enter number of pairs (n): ");
|
|
N = sc.nextInt();
|
|
|
|
int[][] menPref = new int[N][N];
|
|
int[][] womenPref = new int[N][N];
|
|
|
|
System.out.println("\nEnter Men's Preference Lists:");
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
|
|
System.out.println("Preferences of Man " + (char)('A' + i) + ":");
|
|
|
|
for (int j = 0; j < N; j++) {
|
|
char ch = sc.next().charAt(0);
|
|
menPref[i][j] = womanCharToIndex(ch);
|
|
}
|
|
}
|
|
|
|
System.out.println("\nEnter Women's Preference Lists:");
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
|
|
System.out.println("Preferences of Woman " + (char)('W' + i) + ":");
|
|
|
|
for (int j = 0; j < N; j++) {
|
|
char ch = sc.next().charAt(0);
|
|
womenPref[i][j] = manCharToIndex(ch);
|
|
}
|
|
}
|
|
|
|
galeShapley(womenPref, menPref);
|
|
|
|
sc.close();
|
|
}
|
|
}
|