题目:http://acm.hdu.edu.cn/showproblem.php?pid=2544
水题一枚,纯属练手。
My code:
dijstra(优先队列优化)
//STATUS:C++_AC_0MS_320KB #include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> #include<string> #include<vector> #include<queue> #include<stack> #include<map> #include<set> using namespace std; #define Max(x,y) ((x)>(y)?(x):(y)) #define Min(x,y) ((x)<(y)?(x):(y)) #define LL __int64 #define pii pair<int,int> #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define mem(a,b) memset(a,b,sizeof(a)) const int MAX=110,INF=200000000,MOD=100000007; const double esp=1e-6; int dijstra(int s); int n,m; int d[MAX],u[MAX*MAX],v[MAX*MAX],first[MAX],next[MAX*MAX],w[MAX*MAX]; int main() { // freopen("in.txt","r",stdin); int i,j; while(~scanf("%d%d",&n,&m) && (n||m)) { mem(first,-1); for(i=0,j=0;i<m;i++,j++){ scanf("%d%d%d",&u[j],&v[j],&w[j]); next[j]=first[u[j]]; first[u[j]]=j; u[j+1]=v[j],v[j+1]=u[j]; w[j+1]=w[j]; j++; next[j]=first[u[j]]; first[u[j]]=j; } printf("%d\n",dijstra(1)); } return 0; } int dijstra(int s) { int i,j,x,y,e; pii u; priority_queue<pii,vector<pii>,greater<pii> > q; for(i=1;i<=n;i++)d[i]=INF; d[1]=0; u.first=d[1],u.second=1; q.push(u); while(!q.empty()) { u=q.top(); q.pop(); x=u.first,y=u.second; if(x==d[y]){ for(e=first[y];e!=-1;e=next[e]){ if(d[y]+w[e]<d[v[e]]){ d[v[e]]=d[y]+w[e]; q.push(make_pair(d[v[e]],v[e])); } } } } return d[n]; }
SPFA:
//STATUS:C++_AC_15MS_316KB #include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> #include<string> #include<vector> #include<queue> #include<stack> #include<map> #include<set> using namespace std; #define Max(x,y) ((x)>(y)?(x):(y)) #define Min(x,y) ((x)<(y)?(x):(y)) #define LL __int64 #define pii pair<int,int> #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define mem(a,b) memset(a,b,sizeof(a)) const int MAX=110,INF=200000000,MOD=100000007; const double esp=1e-6; int SPFA(int s); int n,m; int d[MAX],u[MAX*MAX],v[MAX*MAX],first[MAX],next[MAX*MAX],w[MAX*MAX],inq[MAX]; int main() { // freopen("in.txt","r",stdin); int i,j; while(~scanf("%d%d",&n,&m) && (n||m)) { mem(first,-1); for(i=0,j=0;i<m;i++,j++){ scanf("%d%d%d",&u[j],&v[j],&w[j]); next[j]=first[u[j]]; first[u[j]]=j; u[j+1]=v[j],v[j+1]=u[j]; w[j+1]=w[j]; j++; next[j]=first[u[j]]; first[u[j]]=j; } printf("%d\n",SPFA(1)); } return 0; } int SPFA(int s) { int i,x,e; queue<int> q; mem(inq,0); for(i=1;i<=n;i++)d[i]=INF; d[1]=0; q.push(1); inq[1]=1; while(!q.empty()) { x=q.front();q.pop(); inq[x]=0; for(e=first[x];e!=-1;e=next[e]){ if(d[x]+w[e]<d[v[e]]){ d[v[e]]=d[x]+w[e]; if(!inq[v[e]]){ inq[v[e]]=1; q.push(v[e]); } } } } return d[n]; }