Problem F: Ordering Tasks
Input: standard input; Output: standard output
Time Limit: 1 second; Memory Limit: 32 MB
(The Joint Effort Contest, Problem setter: Rodrigo Malta Schmidt)
题目链接:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105&page=show_problem&problem=1246
解题思路:
1y 后来看排名排得很后,这种思路效率不高,毕竟有O(n^2)的存在,用二维函数将数据存储为邻接表,digit[i]存储的是i输出时的“优先值”,每次输入两个数时比较两个数的"优先值",如果后一个数b的优先值小于前面那个数a时,就必须将后一个数b纳入a的旗下,因为b的优先值改变了,那么b旗下的其他数的“优先值”也要进行相应的比较后改变,这时就要用到邻接表的存储方式了,最后输入按“优先值”输出
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 110 4 int digit[MAXN], link[MAXN][MAXN]; 5 int main() 6 { 7 8 int i, j, n, m, a, b, temp, flag; 9 while(scanf("%d%d", &n, &m) != EOF) 10 { 11 if(!n && !m) break; 12 for(i=0; i<=n; ++i) digit[i] = link[i][0] = 0; 13 for(i=0; i<m; ++i) 14 { 15 scanf("%d%d", &a, &b); 16 if(digit[b] < digit[a]+1) 17 { 18 digit[b] = digit[a]+1; 19 for(j=1; j<=link[b][0]; ++j) 20 { 21 if(digit[link[b][j]] < digit[b]+1) 22 digit[link[b][j]] = digit[b]+1; 23 } 24 link[a][++link[a][0]] = b; 25 } 26 } 27 temp = 0; 28 for(i=0; i<n; ++i) 29 { 30 flag = 0; 31 for(j=1; j<=n; ++j) 32 if(digit[j] == i) 33 { 34 flag = 1; 35 if(temp++ != 0) printf(" "); 36 printf("%d", j); 37 } 38 if(!flag) break; 39 } 40 printf("\n"); 41 } 42 return 0; 43 }
后来用拓扑排序试了试,不知道是不是因为我用了队列,效率似乎也不见得会变高
Toposort Code
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 110 4 int digit[MAXN], link[MAXN][MAXN], queue[MAXN]; 5 int main() 6 { 7 8 int i, j, n, m, a, b, temp, flag, front, tail; 9 while(scanf("%d%d", &n, &m) != EOF) 10 { 11 if(!n && !m) break; 12 for(i=1; i<=n; ++i) digit[i] = link[i][0] = 0; 13 for(i=0; i<m; ++i) 14 { 15 scanf("%d%d", &a, &b); 16 link[a][++link[a][0]] = b; 17 digit[b]++; 18 } 19 front = tail = 0; 20 for(i=1; i<=n; ++i) 21 if(digit[i] == 0) queue[tail++] = i; 22 while(front != tail) 23 { 24 temp = queue[front++]; 25 if(front != 1) printf(" %d", temp); 26 else printf("%d", temp); 27 for(i=1; i<=link[temp][0]; ++i) 28 if(--digit[link[temp][i]] == 0) queue[tail++] = link[temp][i]; 29 } 30 printf("\n"); 31 } 32 return 0; 33 }