日常满分,哈哈,其实之前写OJ,遇到的dp[i][j] = dp[i][k] + dp[k][j],原来是Floyd算法啊。
哈利·波特要考试了,他需要你的帮助。这门课学的是用魔咒将一种动物变成另一种动物的本事。例如将猫变成老鼠的魔咒是 haha,将老鼠变成鱼的魔咒是 hehe 等等。反方向变化的魔咒就是简单地将原来的魔咒倒过来念,例如 ahah 可以将老鼠变成猫。另外,如果想把猫变成鱼,可以通过念一个直接魔咒 lalala,也可以将猫变老鼠、老鼠变鱼的魔咒连起来念:hahahehe。
现在哈利·波特的手里有一本教材,里面列出了所有的变形魔咒和能变的动物。老师允许他自己带一只动物去考场,要考察他把这只动物变成任意一只指定动物的本事。于是他来问你:带什么动物去可以让最难变的那种动物(即该动物变为哈利·波特自己带去的动物所需要的魔咒最长)需要的魔咒最短?例如:如果只有猫、鼠、鱼,则显然哈利·波特应该带鼠去,因为鼠变成另外两种动物都只需要念 4 个字符;而如果带猫去,则至少需要念 6 个字符才能把猫变成鱼;同理,带鱼去也不是最好的选择。
输入格式:
输入说明:输入第 1 行给出两个正整数 n (≤100)和 m,其中 n 是考试涉及的动物总数,m 是用于直接变形的魔咒条数。为简单起见,我们将动物按 1~n 编号。随后 m 行,每行给出了 3 个正整数,分别是两种动物的编号、以及它们之间变形需要的魔咒的长度(≤100),数字之间用空格分隔。
输出格式:
输出哈利·波特应该带去考场的动物的编号、以及最长的变形魔咒的长度,中间以空格分隔。如果只带1只动物是不可能完成所有变形要求的,则输出 0。如果有若干只动物都可以备选,则输出编号最小的那只。
输入样例:
6 11 3 4 70 1 2 1 5 4 50 2 6 50 5 6 60 1 3 70 4 6 60 3 6 80 5 1 100 2 4 60 5 2 80
输出样例:
4 70
我的AC:
#include<stdio.h> #include<stdlib.h> #define MaxSize 102 const int INFITY = 1000; typedef struct ENode *Edge; struct ENode{ int V1, V2; int Weight; }; typedef struct GNode *PtrToGNode; typedef PtrToGNode MGraph; struct GNode{ int Nv; int Ne; int G[MaxSize][MaxSize]; }; MGraph Init_Graph(); MGraph Build_Graph(); void Insert_Graph(MGraph M, Edge E); void Find_Animal(MGraph M); void Copy_G(MGraph M, int D[][MaxSize]); int Find_Max(int D[][MaxSize], int i, int N); void Floyd(MGraph M, int D[][MaxSize]); int main() { MGraph M; M = Build_Graph(); Find_Animal(M); return 0; } MGraph Build_Graph() { MGraph M; Edge E; M = Init_Graph(); E = (Edge)malloc(sizeof(struct ENode)); for(int i = 0; i < (M ->Ne); i++){ scanf("%d %d %d", &E ->V1, &E ->V2, &E ->Weight); Insert_Graph(M,E); } return M; } MGraph Init_Graph() { MGraph M; M = (MGraph)malloc(sizeof(struct GNode)); scanf("%d %d", &(M ->Nv), &(M ->Ne)); for(int i = 1; i <= (M ->Nv); i++){ for(int j = 1; j <= (M ->Nv); j++){ M ->G[i][j] = INFITY; } M ->G[i][i] = 0; } return M; } void Insert_Graph(MGraph M, Edge E) { M ->G[E ->V1][E ->V2] = E ->Weight; M ->G[E ->V2][E ->V1] = E ->Weight; } void Find_Animal(MGraph M) { int D[MaxSize][MaxSize]; int Animal, MaxDist, MinDist = INFITY; Copy_G(M, D); Floyd(M, D); for(int i = 1; i <= M->Nv; i++) { MaxDist = Find_Max(D, i, M->Nv); if(MaxDist == INFITY){ printf("0\n"); return; } if(MaxDist < MinDist){ MinDist = MaxDist; Animal = i; } } printf("%d %d\n", Animal, MinDist); } void Floyd(MGraph M, int D[][MaxSize]) { for(int k = 1; k <= (M ->Nv); k++){ for(int i = 1; i <= (M ->Nv); i++){ for(int j = 1; j <= (M ->Nv); j++){ if(D[i][j] > D[i][k] + D[k][j]){ D[i][j] = D[i][k] + D[k][j]; } } } } } void Copy_G(MGraph M, int D[][MaxSize]) { for(int i = 1; i <= (M ->Nv); i++) for(int j = 1; j <= (M ->Nv); j++){ D[i][j] = M ->G[i][j]; } } int Find_Max(int D[][MaxSize], int i, int N) { int Maxdist = 0; for(int j = 1; j <= N; j++){ if(D[i][j] > Maxdist){ Maxdist = D[i][j]; } } return Maxdist; }