POJ 1849 Two (树的直径)
题意:一棵树。。然后初始两个推雪机在点s,问如何选择路径使得处理完所有边上的积雪所耗费的汽油最少(走过一条有雪的边和一条没雪的边耗费的汽油一样)
思路:很容易想到,我们应该尽可能不走已经被清理过雪了的边,因为这样很浪费。。。这样不难想到应该是和树的直径有关。但是初始的位置是给定的。。。怎么办?突然发现由于是给了两个推雪机。。所以其实相当于。。。只有一个推雪机&我们可以从任意位置开始推雪。。。第二个问题是。。。对于不在直径上的边。。我们怎么算cost?解决办法是读边的时候进行记录。。。然后求直径的时候记录路径。。。对于一条边。。。只要有一个点不在直径上。。。那么这条边的代价就是2倍。。。
1A蛤蛤蛤
/* ***********************************************
Author :111qqz
Created Time :2016年07月17日 星期日 19时04分49秒
File Name :code/poj/1849.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E5+7;
7vector < pi > edge[N];
8int n,s;
9int lst;
10int beg;
11int d[N];
12bool vis[N];
13bool onpath[N];
14int path[N];
15int ans;
1struct Edge
2{
3 int u,v,w;
1}e[N];
2void init( int n)
3{
4 for ( int i = 1 ; i <= n ; i++) edge[i].clear();
5 ms(path,-1);
6 ms(onpath,false);
7}
1void bfs( int s)
2{
3 ms(d,0);
4 ms(vis,false);
5 queue<int>q;
6 q.push(s);
7 vis[s] = true;
1 while (!q.empty())
2 {
3 int u = q.front();
4 q.pop();
int siz = edge[u].size();
1 for ( int i = 0 ;i < siz; i++)
2 {
3 int v = edge[u][i].fst;
4 int w = edge[u][i].sec;
5 if (vis[v]) continue;
6 path[v] = u;
7 vis[v] = true;
8 d[v] = d[u] + w;
9 q.push(v);
10 }
11 }
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
1 cin>>n>>s;
2 init(n);
3 for ( int i = 1 ;i <= n-1 ; i ++)
4 {
5 int u,v,w;
6 scanf("%d%d%d",&u,&v,&w);
7 e[i].u = u;
8 e[i].v = v;
9 e[i].w = w;
10 edge[u].push_back(make_pair(v,w));
11 edge[v].push_back(make_pair(u,w));
12 }
1 bfs(1);
2 int mx = 0 ;
3 for ( int i = 1 ; i <= n ; i ++)
4 if (d[i]>mx)
5 {
6 mx = d[i];
7 lst = i;
8 }
1 mx = 0 ;
2 ms(path,-1);
3 bfs(lst);
1 for ( int i = 1 ; i <= n ; i++)
2 if (d[i]>mx)
3 {
4 mx = d[i];
5 beg = i ;
6 }
1 ans = mx;
2 int x = beg;
3 //cout<<"bfs ok?"<<endl;
4 while (x!=-1)
5 {
6 //cout<<"x:"<<x<<endl;
7 onpath[x] = true;
8 x = path[x];
9 }
1// cout<<"ans:"<<ans<<endl;
2 for ( int i = 1 ; i <= n-1 ; i++)
3 {
4 int u = e[i].u;
5 int v = e[i].v;
6 int w = e[i].w;
7 if (onpath[u]&&onpath[v]) continue;
8 ans +=w*2;
9 }
printf("%d\n",ans);
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}