UVA--10859--Placing Lampposts--DP
2013-08-08 11:54
281 查看
求两个变量v1和v2在先满足v1最小的情况下,再求v2的最优值,可设 x = M*v1+v2,,其中M是一个很大的值,这样求出的x的最优值就是题目所求,因为在这个式子里面v1起到决定性的作用
参考了一下书上的代码,树上的DP,可以一边dfs一个DP
参考了一下书上的代码,树上的DP,可以一边dfs一个DP
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<cstdlib> #include<map> #include<queue> #include<vector> using namespace std; const int MAXN = 2010; const int M = 2013; vector<int> g[MAXN]; bool vis[MAXN][2]; int d[MAXN][2]; int n,m,T; void init() { int x,y; scanf("%d%d",&n,&m); for(int i=0;i<n;i++)g[i].clear(); memset(vis,0,sizeof(vis)); for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); g[x].push_back(y); g[y].push_back(x); } } int dp(int u,int j,int f) { if(vis[u][j])return d[u][j]; vis[u][j]=1; int sz=g[u].size(); int & ans = d[u][j]; ans = M; for(int i=0;i<sz;i++) { int v=g[u][i]; if(v!=f)ans+=dp(v,1,u); } if(j==0&&f>=0)ans++; //cout<<"ans: "<<ans<<endl; if(j==1||f<0) { int sum=0; for(int i=0;i<sz;i++) { int v=g[u][i]; if(v!=f) { sum+=dp(v,0,u); } } if(f>=0) sum++; //cout<<"sum: "<<sum<<endl; ans=min(ans,sum); } return ans; } void solve() { int ans=0; for(int i=0;i<n;i++) { if(!vis[i][0]) ans+=dp(i,0,-1); } printf("%d %d %d\n",ans/M,m-ans%M,ans%M); } int main() { scanf("%d",&T); while(T--) { init(); solve(); } return 0; }
相关文章推荐
- Uva - 10859 - Placing Lampposts(树形dp)
- uva10859 - Placing Lampposts 无根树转有根树 DP
- uva 10859 Placing Lampposts,树形dp
- UVA 题目10859 Placing Lampposts(树形DP)
- UVA 10859 Placing Lampposts 树形dp(水
- uva 10859 - Placing Lampposts(树形dp)
- 【动态规划】【树形DP】[UVa 10859]Placing Lampposts
- Placing Lampposts - UVa 10859 树形dp
- UVa 10859 Placing Lampposts (树形DP)
- uva_10859_Placing Lampposts( 樹形DP )
- uva 10859 Placing Lampposts (树形dp)
- UVA-10859 - Placing Lampposts(树形DP)
- UVA 10859 Placing Lampposts(树上dp)
- UVA 10859 Placing Lampposts 树形DP
- Placing Lampposts UVA - 10859(树形dp)
- UVa:10859 Placing Lampposts(树形DP)
- uva 10859 Placing Lampposts / Tree DP
- UVA 10859 Placing Lampposts--树形dp
- Placing Lampposts------UVA10859-----DP
- UVA 10859 Placing Lampposts(树DP)