Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others) |
比赛的时候醉了,写了bfs没有调用,数据过了但是TLE了,代码本身还有点小错误,参考了一下大神的代码A了
#include <map>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
#define N 100005
using namespace std;
struct xy{
int u,v,pos,next;
bool f;
}xy[N*4];
queue<int>p;
int v[N],q[N];
bool f[N];
int n,m,cut,ans;
void dfs(int x,int y,int num)
{
if(x==n)
{
ans=num;
return;
}
if(!f[x])
{
f[x]=true;
v[x]=num;
p.push(x);
}
for(int i=q[x];i!=-1;i=xy[i].next)
{
if(xy[i].f)
continue;
if(xy[i].pos==y)
{
xy[i].f=true;
dfs(xy[i].v,y,num);
}
}
}
int bfs(int start,int end)
{
int pos;
p.push(start);
v[start]=0;
f[start]=true;
while(!p.empty())
{
int k=p.front();
p.pop();
for(int i=q[k];i!=-1;i=xy[i].next)
{
if(xy[i].f)
continue;
pos=xy[i].v;
xy[i].f=true;
dfs(pos,xy[i].pos,v[k]+1);
if(ans>0)
break;
}
if(ans>0)
break;
}
return ans;
}
int main(){
while (scanf("%d%d",&n,&m)!=EOF) {
while (!p.empty()) {
p.pop();
}
cut=0;
memset(q,-1,sizeof(q));
memset(f,0,sizeof(f));
memset(v,0xfffffff,sizeof(v));
int x,y,pos;
for(int i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&pos);
xy[cut].u=x;
xy[cut].v=y;
xy[cut].pos=pos;
xy[cut].next=q[x];
xy[cut].f=false;
q[x]=cut++;
xy[cut].u=y;
xy[cut].v=x;
xy[cut].pos=pos;
xy[cut].next=q[y];
xy[cut].f=false;
q[y]=cut++;
}
ans=-1;
ans=bfs(1, n);
printf("%d\n",ans);
}
}