题目:
给一张无向图,求其所有spf节点
Sample Input
1 2 5 4 3 1 3 2 3 4 3 5 0 1 2 2 3 3 4 4 5 5 1 0 1 2 2 3 3 4 4 6 6 3 2 5 5 1 0 0
Sample Output
Network #1 SPF node 3 leaves 2 subnets Network #2 No SPF nodes Network #3 SPF node 2 leaves 2 subnets SPF node 3 leaves 2 subnets
思路:
(明知道这道题是用图算法的一些东西做的,明知道你丫还没看图算法呢,还特么碰。果然,卡了吧,该。)
遍历去掉每个节点,计算去掉该节点之后形成了多少个子网,即为结果。
方案:
先将所给一条条连接快排,得到网络内节点个数amount,从1遍历至amount,生成subnet数组,长度为amount+1:0 1-amount,计算会形成多少个子网。
代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #define MAX 1000*999/2+1 6 7 typedef struct Net 8 { 9 int bin,end; 10 }Net; 11 12 void NetCheck(Net *tab,int con_cnt,int net_cnt); 13 int comp(const void *a,const void *b); 14 15 int main() 16 { 17 Net *tab=(Net *)malloc(sizeof(Net)*MAX); 18 int i,net_cnt=1; 19 while(1) 20 { 21 memset(tab,0,sizeof(Net)*MAX); 22 for(i=0;i<=MAX-1;++i) 23 { 24 scanf("%d",&tab[i].bin); 25 if(tab[i].bin==0) 26 break; 27 scanf("%d",&tab[i].end); 28 } 29 if(i==0) 30 break; 31 if(net_cnt!=1) 32 printf("\n"); 33 NetCheck(tab,i,net_cnt); 34 ++net_cnt; 35 } 36 return 0; 37 } 38 39 void NetCheck(Net *tab,int con_cnt,int net_cnt) 40 { 41 int tmp; 42 int i; 43 for(i=0;i<=con_cnt-1;++i) 44 if(tab[i].bin>tab[i].end) 45 { 46 tmp=tab[i].bin; 47 tab[i].bin=tab[i].end; 48 tab[i].end=tmp; 49 } 50 qsort(tab,con_cnt,sizeof(Net),comp); 51 int amount=tab[con_cnt-1].end; 52 53 int node,sub_net_cnt,start,cur,spf_mark=0,j; 54 int *subnet=(int *)malloc(sizeof(int)*(amount+1)); 55 printf("Network #%d\n",net_cnt); 56 for(node=1;node<=amount;++node) 57 { 58 if(node==1) 59 start=2; 60 else 61 start=1; 62 sub_net_cnt=0; 63 memset(subnet,0,sizeof(int)*(amount+1)); 64 subnet[node]=-1; 65 while(start<=amount) 66 { 67 subnet[start]=++sub_net_cnt; 68 for(i=0;i<=con_cnt-1;++i) 69 { 70 if(tab[i].bin==node||tab[i].end==node) 71 continue; 72 if(subnet[tab[i].bin]!=subnet[tab[i].end]) 73 { 74 if(subnet[tab[i].bin]==0) 75 subnet[tab[i].bin]=subnet[tab[i].end]; 76 else if(subnet[tab[i].end]==0) 77 subnet[tab[i].end]=subnet[tab[i].bin]; 78 else if(subnet[tab[i].bin]<subnet[tab[i].end]) 79 { 80 --sub_net_cnt; 81 for(j=1;j<=amount;++j) 82 if(subnet[j]==subnet[tab[i].end]) 83 subnet[j]=subnet[tab[i].bin]; 84 subnet[tab[i].end]=subnet[tab[i].bin]; 85 } 86 else 87 { 88 --sub_net_cnt; 89 for(j=1;j<=amount;++j) 90 if(subnet[j]==subnet[tab[i].bin]) 91 subnet[j]=subnet[tab[i].end]; 92 subnet[tab[i].bin]=subnet[tab[i].end]; 93 } 94 } 95 } 96 while(start<=amount&&subnet[start]!=0) 97 ++start; 98 } 99 if(sub_net_cnt>1) 100 { 101 spf_mark=1; 102 printf(" SPF node %d leaves %d subnets\n",node,sub_net_cnt); 103 } 104 } 105 if(spf_mark==0) 106 printf(" No SPF nodes\n"); 107 } 108 109 int comp(const void *a,const void *b) 110 { 111 return ((Net *)a)->end-((Net *)b)->end; 112 }
记录:
我勒个去的到目前这版,在基本代至上所进行过的修改:修改了输出规格(每两份网络中间空一行而不是每份网络之后空一行),修改了排序基准以获得最大网络节点号,但还是找不到错误在哪里,结果一直是wrong answer……我决定先放在这里了,恶心了。
140205 1237 第三次修改:修改了当跨层数子网合并时会出现的子网序号错乱问题,依旧wrong answer……
心得:
革命尚未成功,同志们回头努力。
浙公网安备 33010602011771号