Moderator: Board moderators
Remove After ACgoodwill wrote:You may find this O(n) algorithm interesting (no need to know how many color there are).
http://citeseer.ist.psu.edu/494676.html
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MAX 10004
#define NCOLOR 10
unsigned long INF = (1 << 29);
int degree[MAX], graph[MAX][MAX], cost[MAX][NCOLOR];
int main()
{
register int m, p;
int n, i, j, k, color;
string line, first;
while(cin >> n) {
if (n == 0) break;
cin.ignore();
memset(degree, 0, sizeof(degree));
memset(graph, 0, sizeof(graph));
for (i = 0; i < n; i++) {
getline(cin, line);
stringstream sstr;
sstr << line;
sstr >> first;
first.erase(first.size()-1, 1);
stringstream sstr2;
sstr2 << first;
sstr2 >> j;
while(sstr >> k) {
if (k > j)
graph[j][degree[j]++] = k;
else
graph[k][degree[k]++] = j;
}
}
/* for (i = 0; i < n; i++) {
cout << i << ": ";
for (j = 0; j < degree[i]; j++)
cout << graph[i][j] << ' ';
cout << endl;
}
cout << endl;*/
for (i = n-1; i >= 0; i--) {
if (degree[i] == 0) {
for (j = 0; j < NCOLOR; j++)
cost[i][j] = j + 1;
}
else {
for (color = 0; color < NCOLOR; color++) {
k = 0;
for (j = 0; j < degree[i]; j++) {
m = INF;
for (p = 0; p < NCOLOR; p++) {
if (p == color) continue;
if (cost[graph[i][j]][p] < m)
m = cost[graph[i][j]][p];
}
k += m;
}
cost[i][color] = k + color + 1;
}
}
}
m = cost[0][0];
for (i = 1; i < degree[0]; i++)
if (cost[0][i] < m)
m = cost[0][i];
cout << m << endl;
}
return 0;
}

for(i=0; i<n; ++i)
{
gets(line);
p = line;
sscanf(p, "%d%n", &from, &len);
p += len;
while(*p)
{
if(sscanf(p, "%d%n", &to, &len) == 1)
{
v[from].push_back(to);
}
p += len;
}
}Users browsing this forum: No registered users and 0 guests