Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
方法不同,效率真是天差地别啊贴上第一份代码,232K 219MS 没有优化,使用效率极低的方法:DFS+BFS #include <stdio.h> #include <queue> #include <memory.h> #define MAXN 101 int headlist[MAXN],vexnum; using namespace std; typedef struct { int start,end,next; }Edge; Edge de[4501]; int visited[MAXN]; bool flag[MAXN]; bool DFS(int k,int d) { if(k==d) return true; visited[k]=1; for(int i=headlist[k];i!=-1;i=de[i].next) if(!visited[de[i].end]&&DFS(de[i].end,d)) return true; return false; } int BFS(int k) { queue<int>q; int sum=-1,temp,i; visited[k]=1; q.push(k); while(!q.empty()) { temp=q.front(); sum++; q.pop(); for(i=headlist[temp];i!=-1;i=de[i].next) { if(!visited[de[i].end]) { visited[de[i].end]=1; q.push(de[i].end); } } } return sum; } int main() { int N,M,i,j,ans,temp,len; while(scanf("%d %d",&N,&M)!=EOF) { vexnum=N; memset(headlist,-1,sizeof(headlist)); for(i=0;i<M;++i) { scanf("%d %d",&de[i].start,&de[i].end); de[i].next=headlist[de[i].start]; headlist[de[i].start]=i; } ans=0; for(i=1;i<=vexnum;++i) { len=0; for(j=1;j<=vexnum;++j) { memset(visited,0,sizeof(visited)); if(i!=j&&DFS(j,i)==true) len++; } memset(visited,0,sizeof(visited)); if(len+BFS(i)==vexnum-1) ans++; } printf("%d\n",ans); } return 0; } 第二份:204K 0MS #include <stdio.h> #include <memory.h> #define MAXN 101 #define INF 0x3f3f3f3f int dis[MAXN][MAXN],vexnum; void Floyd() { int i,j,k; for(k=1;k<=vexnum;++k) { for(i=1;i<=vexnum;++i) { if(dis[i][k]==INF) continue; for(j=1;j<=vexnum;++j) { if(dis[k][j]==INF) continue; if(dis[i][j]>dis[i][k]+dis[k][j]) dis[i][j]=dis[i][k]+dis[k][j]; } } } int ans=0,num; for(i=1;i<=vexnum;++i) { num=0; for(j=1;j<=vexnum;++j) { if(dis[i][j]!=INF&&i!=j) num++; if(dis[j][i]!=INF&&i!=j) num++; } if(num==vexnum-1) ans++; } printf("%d\n",ans); } int main() { int N,M,a,b; while(scanf("%d %d",&N,&M)!=EOF) { vexnum=N; memset(dis,INF,sizeof(dis)); while(M--) { scanf("%d %d",&a,&b); dis[a][b]=1; } Floyd(); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator