Walk Through the Forest UVA - 10917 DAG上的图
2017-04-20 11:18
253 查看
居然AC 了,,
越来越不自信了。。
还以为自己在dfs的时候肯定会有地方错。。。然后用dp的时候可能也会错。。
结果过了。。
这道题让我对于DAG的dp算法有了跟进一步的了解。。。
越来越不自信了。。
还以为自己在dfs的时候肯定会有地方错。。。然后用dp的时候可能也会错。。
结果过了。。
这道题让我对于DAG的dp算法有了跟进一步的了解。。。
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<string> #include<cstring> #include<iomanip> #include<iostream> #include<stack> #include<cmath> #include<map> #include<vector> #define ll long long #define inf 0x3f3f3f3f #define INF 1e9 #define bug1 cout<<"bug1"<<endl; #define bug2 cout<<"bug2"<<endl; #define bug3 cout<<"bug3"<<endl; using namespace std; #define sf scanf #define pf printf #define mem(a,b) memset(a,b,sizeof(a)); const int maxn=1005; int n,m; int vis[maxn]; int d[maxn]; int dp[maxn]; int head[maxn]; struct Edge{ int v,c,nxt; }edge[maxn*maxn]; int tol; void addedge(int u,int v,int c){ edge[tol].v=v;edge[tol].c=c; edge[tol].nxt=head[u]; head[u]=tol++; } void spfa(int s){ queue<int>q; mem(d,inf); mem(vis,0); q.push(s); d[s]=0; vis[s]=1; while(!q.empty()){ int u=q.front();q.pop(); vis[u]=0; for(int i=head[u];~i;i=edge[i].nxt){ int v=edge[i].v; if(d[v]>d[u]+edge[i].c){ d[v]=d[u]+edge[i].c; if(!vis[v]){ vis[v]=1;q.push(v); } } } } } vector<int>sons[maxn]; void dfs1(int u){ vis[u]=1; if(u==2)return; for(int i=head[u];~i;i=edge[i].nxt){ int v=edge[i].v; if(d[v]<d[u]){ sons[u].push_back(v); if(!vis[v])dfs1(v); } } } int dfs(int u){ if(u==2)return dp[u]=1; if(dp[u]!=-1)return dp[u]; dp[u]=0; for(int i=0;i<sons[u].size();++i){ dp[u]+=dfs(sons[u][i]); } return dp[u]; } int main(){ while(~sf("%d%d",&n,&m)&&n){ tol=0;mem(head,-1); for(int i=1;i<=m;++i){ int u,v,c; sf("%d%d%d",&u,&v,&c); addedge(u,v,c); addedge(v,u,c); } spfa(2); mem(vis,0); for(int i=1;i<=n;++i){ sons[i].clear(); } dfs1(1); mem(dp,-1); dfs(1); pf("%d\n",dp[1]); } }
相关文章推荐
- UVA - 10917 Walk Through the Forest(最短路的DAG)
- UVA 10917 Walk Through the Forest(dijkstra+DAG上的dp)
- UVA 10917 Walk Through the Forest
- uva 10917 Walk Through the Forest(最短路+DP路径,4级)
- UVa 10917 Walk Through the Forest(最短路+DP)
- UVA10917 Walk Through the Forest
- UVA 10917 - Walk Through the Forest(最短路`dijksta+DP)
- UVA10917 Walk Through the Forest
- uva 10917 Walk Through the Forest
- UVA - 10917 Walk Through the Forest (最短路+DP)
- UVA 10917(p330)----Walk through the Forest
- UVa 10917 A Walk Through the Forest
- Uva 10917 - Walk Through the Forest 最短路
- UVa 10917 - Walk Through the Forest(Dijkstra + DFS)
- UVA10917 Walk Through the Forest (dijkstra + dfs)
- UVA10917 A Walk Through the Forest
- UVA 10917 Walk Through the Forest
- UVa10917 Walk Through the Forest
- UVA 10917 Walk Through the Forest(最短路+dp)
- UVA 10917 - Walk Through the Forest(最短路优化DP)