2017-03-18 Ice_cream’s world II

本文探讨了有向图中的最小生成树问题,通过构造一个虚拟的根节点并使用朱刘算法来解决这一难题。文章提供了详细的算法实现过程及代码示例,并对比了使用Kruskal算法时的不同表现。

description

 After awarded lands to ACMers, the queen want to choose a city be her capital. This is an important event in ice_cream world, and it also a very difficult problem, because the world have N cities and M roads, every road was directed. Wiskey is a chief engineer in ice_cream world. The queen asked Wiskey must find a suitable location to establish the capital, beautify the roads which let capital can visit each city and the project’s cost as less as better. If Wiskey can’t fulfill the queen’s require, he will be punishing. 

Input

Every case have two integers N and M (N<=1000, M<=10000), the cities numbered 0…N-1, following M lines, each line contain three integers S, T and C, meaning from S to T have a road will cost C.

Output

If no location satisfy the queen’s require, you must be output “impossible”, otherwise, print the minimum cost in this project and suitable city’s number. May be exist many suitable cities, choose the minimum number city. After every case print one blank.

Sample Input

3 1
0 1 1

4 4
0 1 10
0 2 10
1 3 20
2 3 30

Sample Output

impossible

40 0

solution

求的是有向最小生成树,拟定一个虚根做朱刘算法,ans如果大于或等于2*sum+2,这意味着这个图本身(不包括虚根)时,是不连通的,所以输出impossible;其他则输出ans-sum和mr-m-1,mr是我们在做朱刘算法是记录下的最后一次离虚根最近的边的编号,-m是因为我们在建立虚根时,将虚根和每一个点连接起来了,-1是因为我们为了给这一题的虚根腾出位置,在存点的时候认为的给每一个输入点+1,因为原来的点可能会存在0;

Code

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
#define N 10001
#define bobo 100000000
using namespace std;
int n,m,cnt,sum,mr,tot,rec;
int co[N],fr[N],circ[N],num[N];
struct node{
  int fr,to,w;
}q[3*N];
int zhuliu(int sou,int whole)
  {
    rec=0;
    while(1)
      {
    memset(fr,-1,sizeof(fr));
    memset(circ,-1,sizeof(circ));
    memset(num,-1,sizeof(num));
    for (int i=0;i<=whole;++i) co[i]=bobo;
    for(int i=1;i<=m+n;i++)
      {
        int a=q[i].fr,b=q[i].to,c=q[i].w;
        if(c<co[b]&&a!=b)
          {
        co[b]=c;
        fr[b]=a;
        if(a==sou) mr=i;
          }
      }
    tot=0;
    co[sou]=0;
    for(int i=0;i<=whole;i++)
      {
        rec+=co[i];
        int bj=i;
        while(bj!=sou&&circ[bj]!=i&&num[bj]==-1) circ[bj]=i,bj=fr[bj];
        if(bj!=sou&&num[bj]==-1)
          {
        for(int hh=fr[bj];hh!=bj;hh=fr[hh]) num[hh]=tot;
        num[bj]=tot++;
          }
      }
    if(!tot) break;
    for(int i=0;i<=whole;i++) if(num[i]==-1) num[i]=tot++;
    for(int i=1;i<=m+n;i++)
      {
        int a=q[i].fr,b=q[i].to;
        q[i].fr=num[a];
        q[i].to=num[b];
        if(q[i].fr!=q[i].to) q[i].w-=co[b];
      }
    whole=tot-1;
    sou=num[sou];
      }
    return rec;
  }
int main()
{
  while(scanf("%d%d",&n,&m)!=EOF)
    {
      memset(q,-1,sizeof(q));
      int a,b,c;
      cnt=0;sum=0;
      for(int i=1;i<=m;i++)
    {
      scanf("%d%d%d",&a,&b,&c);
      q[i].fr=a+1,q[i].to=b+1,q[i].w=c;
      sum+=c;
    }
      sum++;
      for(int i=m+1;i<=m+n;i++)
    q[i].fr=0,q[i].to=i-m,q[i].w=sum;
      int ans=zhuliu(0,n);
      if(ans>=sum*2) printf("impossible\n\n");
      else printf("%d %d\n\n",ans-sum,mr-m-1);
    }
}

出于私心,我还要发一个没学朱刘算法前打的kruscal会超时(严重)的code

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
#define N 
using namespace std;
int n,m;
int fa[1001];
struct line
{
  int fr,to,w;
  bool operator <(const line &a) const
  {
    return w<a.w;
  }
}q[10001];
int findset(int x)
{
  return fa[x]==x?x:(fa[x]=findset(fa[x]));
}
int unionset(int x,int y)
{
  return fa[findset(y)]=findset(x);
}
int main()
{
  while(scanf("%d%d",&n,&m))
    {
      memset(fa,0,sizeof(fa));
      memset(q,0,sizeof(q));
      for(int i=0;i<n;i++)
    fa[i]=i;
      for(int i=0;i<m;i++)
    {
      scanf("%d%d%d",&q[i].fr,&q[i].to,&q[i].w);
    }
      sort(q,q+m);
      ll ans=0;
      for(int i=0;i<m;i++)
    {
      int fr=q[i].fr;
      int to=q[i].to;
      if(findset(fr)==findset(to)) continue;
      ans+=q[i].w;
      unionset(fr,to);
    }
      int pd=findset(0);
      bool falg=false;
      for(int i=1;i<n;i++)
    if(findset(i)!=pd) falg=true;
      if(!falg)
    printf("%lld %d\n",ans,findset(n-1));
      else
    printf("impossible\n");
    }
  return 0;
}

那个看朱刘算法的话,看这个
大概思想就是,不断的把途中的环进行缩点,然后更新点的编号和边权值,一直到没有一个环时,此时得到的ans就是有向的MST的总边权值;
http://blog.youkuaiyun.com/l123012013048/article/details/48375819

#!/usr/bin/env python3 from typing import Optional, Tuple import pickle from pathlib import Path from yourdfpy import URDF from functools import partial from tempfile import TemporaryDirectory from tqdm.auto import tqdm import torch as th import copy import trimesh from icecream import ic import numpy as np from matplotlib import pyplot as plt import torch.nn.functional as F import einops from pkm.env.scene.dgn_object_set import DGNObjectSet from pkm.env.scene.acronym_object_set import AcronymObjectSet from pkm.env.scene.combine_object_set import CombinedObjectSet from pkm.env.scene.filter_object_set import FilteredObjectSet, dataset_hasattr from pkm.models.common import merge_shapes from pkm.util.path import ensure_directory from pkm.util.math_util import ( apply_pose_tq, invert_pose_tq, compose_pose_tq, quat_rotate, matrix_from_pose ) from pkm.util.torch_util import dcn from pkm.data.transforms.sdf.sdf_cvx_set_th3 import SignedDistanceTransform from pkm.data.transforms.sdf.sdf_cvx_set_th3 import IsInHulls from pkm.data.transforms.df_th3 import DistanceTransform from pkm.data.transforms.aff import CheckGripperCollisionV2 def sample_pose(size: Tuple[int, ...], bound: th.Tensor): pose = th.empty(merge_shapes(size, 7), dtype=bound.dtype, device=bound.device) scale = (bound[..., 1, :] - bound[..., 0, :]) offset = bound[..., 0, :] pose[..., :3].uniform_().mul_(scale).add_(offset) pose[..., 3:7].normal_() pose[..., 3:7] /= th.linalg.norm(pose[..., 3:7], dim=-1, keepdim=True) return pose class ObjectSetDataset(th.utils.data.Dataset): def __init__(self, meta, min_radius: float = 0.04, max_radius: float = 0.12): self.meta = meta self.keys = list(self.meta.keys()) self.r_min = min_radius self.r_max = max_radius def __len__(self): return len(self.meta) def __getitem__(self, i): cloud = self.meta.cloud(self.keys[i]) radius = np.linalg.norm(cloud, axis=-1).max() # radius2 = np.linalg.norm(cloud - cloud.mean(axis=-1, keepdims=True), axis=-1).max() # print(radius, radius2) scale = np.random.uniform(self.r_min, self.r_max) / radius return { 'cloud': cloud * scale, 'key': self.keys[i], 'scale': scale } def main(): # Configure generation. device: str = 'cuda:0' batch_size: int = 64 repeat: int = 40 sigma: float = 0.05 delta: float = 0.03 min_radius: float = 0.04 max_radius: float = 0.12 out_dir: str = ensure_directory('/tmp/col-12-2048') table_dim: Tuple[float, float, float] = (0.4, 0.5, 0.4) initial_count: int = 0 export_data: bool = True show_result: bool = False # Allow restarting from where the process crashed last time. if Path(out_dir).is_dir(): initial_count = len(list(Path(out_dir).glob('*.pkl'))) # Prepare dataset. if True: meta = DGNObjectSet(DGNObjectSet.Config( data_path='/input/DGN/meta-v8/', cloud_path='/input/DGN/meta-v8/cloud-2048/' )) dataset = ObjectSetDataset(meta, min_radius, max_radius) else: dgn_object_set = DGNObjectSet(DGNObjectSet.Config( data_path='/input/DGN/meta-v8/', cloud_path='/input/DGN/meta-v8/cloud-2048/' )) acr_object_set = AcronymObjectSet(AcronymObjectSet.Config( data_path='/input/ACRONYM/meta-v1/', cloud_path='/input/ACRONYM/meta-v1/cloud-2048', )) all_object_set = CombinedObjectSet([dgn_object_set, acr_object_set]) all_object_set = FilteredObjectSet( all_object_set, filter_fn=partial( dataset_hasattr, all_object_set, 'cloud')) dataset = ObjectSetDataset(all_object_set) loader = th.utils.data.DataLoader(dataset, batch_size=batch_size, drop_last=False) # Prepare collision checker. collision_fn = CheckGripperCollisionV2( device=device) # Configure pose sampler. tx, ty, tz = table_dim workspace = th.as_tensor([ [-0.6 * tx, -0.6 * ty, tz - 0.05], [+0.6 * tx, +0.6 * ty, tz + 0.25] ], dtype=th.float, device=device) # Repeat and generate ! count: int = initial_count for repeat in tqdm(range(repeat)): for data in tqdm(loader): with th.no_grad(): obj_cloud = data['cloud'].to( dtype=th.float, device=device) # obj_cloud = workspace[0] + th.rand((2048, 3), # device=device) * (workspace[1] - workspace[0]) # print(obj_cloud.min(dim=0)) # print(obj_cloud.max(dim=0)) # Sample scene configuration. hand_pose = sample_pose( obj_cloud.shape[0], workspace) # world_from_hand objt_pose = sample_pose( obj_cloud.shape[0], workspace) # world_from_obj # objt_pose = hand_pose hand_from_obj = compose_pose_tq( invert_pose_tq(hand_pose), objt_pose) obj_cloud_wrt_hand = apply_pose_tq( hand_from_obj[:, None, :], # N,1,7 obj_cloud) d, g = collision_fn(obj_cloud_wrt_hand) i = th.argmin(d, dim=-1, keepdim=True) d = th.take_along_dim(d, i, dim=-1).squeeze(dim=-1) g = th.take_along_dim(g, i[..., None], dim=-2).squeeze(dim=-2) # Gradient direction, in world frame u = quat_rotate(hand_pose[..., 3:7], g) # Move gripper near the surface of the object. # We additionally apply a bit of offset to # increase the proportion of patches' intersections. # d_ = d d_ = d + sigma * th.randn_like(d) + delta # d_ = d + th.rand_like(d) txn = -d_[..., None] * u objt_pose[..., :3].add_(txn) # Apply new transform and then recompute SDF values. hand_from_obj = compose_pose_tq( invert_pose_tq(hand_pose), objt_pose) obj_cloud_wrt_hand = apply_pose_tq( hand_from_obj[:, None, :], # N,1,7 obj_cloud) d, g = collision_fn(obj_cloud_wrt_hand) # Determine contact points. contact_flag = (d <= 0) # contact_flag = m # print('contact_flag', contact_flag.shape) # ic(th.mean(contact_flag.any(dim=-1).float())) if True: tmp = apply_pose_tq( objt_pose[:, None, :], # N,1,7 obj_cloud) zmin = tmp[..., 2].min(dim=-1).values target = table_dim[2] + 0.1 * th.rand( size=(obj_cloud.shape[0],), device=obj_cloud.device) dz = target - zmin objt_pose[..., 2] += dz hand_pose[..., 2] += dz # EXPORT DATA. if export_data: def __export(count): objt_cloud = apply_pose_tq(objt_pose[..., None, :], obj_cloud) p = dcn(hand_pose) o = dcn(objt_pose) c = dcn(objt_cloud) f = dcn(contact_flag) k = dcn(data['key']) s = dcn(data['scale']) for i in range(obj_cloud.shape[0]): with open(F'{out_dir}/{count:06d}.pkl', 'wb') as fp: pickle.dump({ 'key': k[i], 'hand_pose': p[i], 'object_pose': o[i], 'object_cloud': c[i], 'contact_flag': f[i], 'rel_scale': s[i] }, fp) count += 1 return count count = __export(count) if show_result: def __visualize(): objt_matrix = matrix_from_pose(objt_pose[..., 0:3], objt_pose[..., 3:7]) hand_matrix = matrix_from_pose(hand_pose[..., 0:3], hand_pose[..., 3:7]) objt_cloud = apply_pose_tq(objt_pose[..., None, :], obj_cloud) objt_matrix = dcn(objt_matrix) hand_matrix = dcn(hand_matrix) objt_cloud = dcn(objt_cloud) ctct_flag = dcn(contact_flag) for To, Th, Xo, Cf in zip(objt_matrix, hand_matrix, objt_cloud, ctct_flag): hand_mesh = copy.deepcopy(collision_fn.mesh) hand_mesh.apply_transform(Th) objt_cloud = trimesh.PointCloud(Xo) objt_cloud.visual.vertex_colors = np.where( Cf[..., None], (255, 0, 0), (0, 0, 255)) hand_hull_mesh = copy.deepcopy(collision_fn.hull_mesh) hand_hull_mesh.apply_transform(Th) hand_hull_mesh.visual.vertex_colors = (0, 255, 0) table_mesh = trimesh.creation.box((0.4, 0.5, 0.4)) table_xfm = np.eye(4) table_xfm[2, 3] = +0.2 table_mesh.apply_transform(table_xfm) trimesh.Scene([ # hand_mesh, objt_cloud, hand_hull_mesh, trimesh.creation.axis(), table_mesh ]).show() # return __visualize() if __name__ == '__main__': main() 逐行分析代码
最新发布
08-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值