repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
maruinen/FullereneViewer
|
src/ShutUp.h
|
<filename>src/ShutUp.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __SHUTUP_H__
#define __SHUTUP_H__
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#endif /* __SHUTUP_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Ring.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __RING_H__
#define __RING_H__
#include "InteractiveRegularPolygon.h"
#include "List.h"
#include "Carbon.h"
extern int *pentagon_cellophane_colors;
extern int pentagon_strong_cellophane_colors[];
extern int pentagon_tint_cellophane_colors[];
extern int pentagon_mono_chrome_cellophane_colors[];
class Bond;
class CarbonAllotrope;
class Ring : public InteractiveRegularPolygon {
// friend classes & functions
// members
private:
int p_number_of_carbons;
List<Carbon> p_carbons;
double p_radius;
int p_clockwise;
int p_ring_color;
// private tools
private:
void p_make_carbons(CarbonAllotrope* ca, Bond* bond_connection);
void p_make_carbons(CarbonAllotrope* ca, const int* carbon_sequence_nos);
void p_print_POVRay_semitransparent(FILE* fptr, const Vector3& one,
const Vector3& two, const Vector3& three) const;
Vector3
p_clip_by_Z_non_negative(const Vector3& negative, const Vector3& positive) const;
void p_print_POVRay_semitransparent_clipped_by_Z_non_negative(FILE* fptr,
Vector3 one,
Vector3 two,
Vector3 three) const;
// constructors & the destructor
public:
Ring(int number_of_carbons, CarbonAllotrope* ca); /* ring only but not carbons/bonds */
Ring(CarbonAllotrope* ca, int number_of_carbons);
Ring(CarbonAllotrope* ca, int number_of_carbons, Bond* bond_connection);
Ring(CarbonAllotrope* ca, int number_of_carbons, Carbon* carbon_connection);
Ring(CarbonAllotrope* ca, int number_of_carbons, const int* carbon_sequence_nos);
virtual ~Ring();
Ring& operator = (const Ring& you); /* dont use */
void copy_from(const CarbonAllotrope* ca, const Ring* you);
// distance
public:
int distance_to_set();
// determining normal vector
public:
void reset_clockwise();
void set_clockwise(Carbon* from, Carbon* to, bool locally = false);
void set_clockwise_locally();
// interactions
// I/O
public:
void print_structure(int indent = 0, bool deep = true) const;
void print_POVRay_scene_description(const CarbonAllotrope* ca, FILE* fptr) const;
void print_POVRay_scene_description(const CarbonAllotrope* ca, FILE* fptr,
const Matrix3& rot, const Vector3& move,
bool clipped_by_Z_non_negative) const;
virtual void draw_semitransparent_by_OpenGL(bool selection, bool frontface) const;
// member accessing methods
// attributes
public:
int number_of_carbons() const { return p_number_of_carbons; }
virtual Vector3 get_center_location() const;
virtual Vector3 get_normal() const;
Carbon* get_carbon(int index);
const Carbon* get_carbon(int index) const;
Bond* get_bond_after(int index);
Bond* get_bond_before(int index);
void set_color(int color);
};
#endif /* __RING_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/PipeHandler.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __PIPEHANDLER_H__
#define __PIPEHANDLER_H__
#include "ReadHandler.h"
#define BUFFER_SIZE 1024
class Process;
class Range;
class Collector;
class PipeHandler : public ReadHandler {
// friend classes & functions
// members
private:
char p_buffer[BUFFER_SIZE];
int p_data_len;
int p_line_top;
int p_line_len;
Process* p_process;
Range* p_assigned_range;
Collector* p_assigned_collector;
// private tools
private:
bool p_receive();
bool p_read_line();
// constructors & the destructor
public:
PipeHandler(Process* process);
virtual ~PipeHandler();
// comparators
// member accessing methods
protected:
virtual ReadHandlerResult call();
};
#endif /* __PIPEHANDLER_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Posture.h
|
<reponame>maruinen/FullereneViewer<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __POSTURE_H__
#define __POSTURE_H__
#include "Matrix3.h"
#include "Vector3.h"
class Posture {
// members
public:
Matrix3 posture;
bool fixed;
Matrix3 fixed_posture;
Matrix3 last_posture;
Vector3 next_moment;
// constructors & the destructor
public:
Posture() : posture(), fixed(false), fixed_posture(), last_posture(), next_moment() { }
~Posture() { }
Posture& operator = (const Posture& you); /* dont use */
// stability
bool stabled() const { return last_posture == posture; }
};
#endif /* __POSTURE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/DistanceSummaryLine.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __DISTANCESUMMARYLINE_H__
#define __DISTANCESUMMARYLINE_H__
#include "Object.h"
#include "MyString.h"
class DistanceSummaryLine : public Object {
// friend classes & functions
// members
private:
static int s_next_sequence;
private:
MyString p_line;
// private tools
private:
static bool p_get_number(const char*& ptr, int& number);
// constructors & the destructor
public:
DistanceSummaryLine(const char* line);
~DistanceSummaryLine();
// comparators
public:
int compare(const DistanceSummaryLine* you) const;
// I/O
public:
void print() const;
// member accessing methods
};
#endif /* __DISTANCESUMMARYLINE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Qt/ConfigurationDialog.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CONFIGURATIONDIALOG_H__
#define __CONFIGURATIONDIALOG_H__
#include <QDialog>
namespace Ui {
class ConfigurationDialog;
}
class ConfigurationDialog : public QDialog
{
Q_OBJECT
public:
explicit ConfigurationDialog(QWidget *parent = 0);
~ConfigurationDialog();
private slots:
void slot_accept();
void slot_reject();
private:
Ui::ConfigurationDialog *ui;
};
#endif /* __CONFIGURATIONDIALOG_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Representations.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __REPRESENTATIONS_H__
#define __REPRESENTATIONS_H__
#include "Object.h"
#include "Set.h"
#include "Representation.h"
class Representations : public Object {
// friend classes & functions
// members
private:
Set<Representation> p_reps;
int p_number_of_automorphisms;
// private tools
// constructors & the destructor
public:
Representations();
virtual ~Representations();
Representations& operator = (const Representations& youd); /* dont use */
// comparators
public:
int compare(const Representations* you) const;
// I/O
public:
void print() const;
// member accessing methods
public:
void add_up_to_isomorphism(Representation* you);
int length() const { return p_reps.length(); }
Representation* get_representation(int index);
const Representation* get_representation(int index) const;
int number_of_automorphisms();
};
#endif /* __REPRESENTATIONS_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/DistanceMatrix.h
|
<filename>src/DistanceMatrix.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __DISTANCEMATRIX_H__
#define __DISTANCEMATRIX_H__
#include <stdio.h>
#include "Object.h"
class CarbonAllotrope;
class DistanceMatrix : public Object {
// friend classes & functions
// members
private:
int p_number;
int p_distances[12][12];
int p_sequence_nos[12];
// private tools
private:
void p_initialize();
int p_seq_no_to_index(int seq_no);
void p_print_as_table(FILE* fptr = stdout) const;
void p_print_as_line(FILE* fptr = stdout) const;
void p_sort(int i, int j);
int p_select_minimum(int top);
void p_swap(int i1, int i2);
// constructors & the destructor
public:
DistanceMatrix();
DistanceMatrix(CarbonAllotrope* ca);
DistanceMatrix(const DistanceMatrix& you);
DistanceMatrix(const DistanceMatrix& you, int* group, int no);
~DistanceMatrix();
DistanceMatrix& operator = (const DistanceMatrix& you);
// type converters
public:
void normalize();
// comparators
// I/O
public:
void print_as_table(FILE* fptr = stdout) const;
void print_as_line(FILE* fptr = stdout) const;
// member accessing methods
public:
void set_distance(int seq_no1, int seq_no2, int distance);
int get_distance(int seq_no1, int seq_no2);
int grouping(int max_distance, int* group) const;
};
#endif /* __DISTANCEMATRIX_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Statistics.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __STATISTICS_H__
#define __STATISTICS_H__
#include "List.h"
#include "Vector3.h"
class Statistics {
// friend classes & functions
// members
private:
List<Vector3> p_samples;
int p_sum;
Vector3 p_sum_of_samples;
Vector3 p_sum_of_samplesamples;
double p_sum_of_yzs;
double p_sum_of_zxs;
double p_sum_of_xys;
// private tools
// constructors & the destructor
public:
Statistics();
~Statistics();
Statistics& operator = (const Statistics& you); /* dont use */
// type converters
Matrix3 variance_covariance_matrix() const;
// comparators
// math operators
// I/O
// class decision
// member accessing methods
void sample(Vector3* s);
void average_to_zero();
Vector3 get_average() const;
};
#endif
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Fullerenes.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __FULLERENES_H__
#define __FULLERENES_H__
#include <limits.h>
#include "Set.h"
#include "MinimumRepresentation.h"
#include "Stack.h"
#include "Step.h"
enum StepAlgorithm {
STEP_ALGORITHM_COPY_BRANCH = 1,
STEP_ALGORITHM_FORWARD = 2,
STEP_ALGORITHM_BACKWARD = 3
};
class Fullerenes {
// friend classes & functions
// members
private:
Set<MinimumRepresentation> p_patterns;
// private tools
void p_step_copy_branch(Generator& gen, int maximum_number_of_carbons,
bool symmetric, int close, bool shallow_copy);
void p_step_forward(Generator& gen, int maximum_number_of_carbons,
bool symmetric, int close);
void p_step_ei_yah(const char* generator_formula, int maximum_number_of_carbons,
bool symmetric, int maximum_vertices_of_polygons, int close,
StepAlgorithm step_algorithm = STEP_ALGORITHM_BACKWARD);
// constructors & the destructor
public:
Fullerenes(const char* generator_formula, int maximum_number_of_carbons,
bool symmetric = true, int maximum_vertices_of_polygons = 6,
int close = INT_MAX,
StepAlgorithm step_algorithm = STEP_ALGORITHM_BACKWARD);
~Fullerenes();
// type converters
// comparators
// math operators
// I/O
// class decision
// member accessing methods
public:
int number_of_patterns() const;
const Fullerene* get_pattern(int index) const;
void add_fullerene(Fullerene* pat);
};
#endif /* __FULLERENES_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/AcceptHandler.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __ACCEPTHANDLER_H__
#define __ACCEPTHANDLER_H__
#include <stdio.h>
#include "ReadHandler.h"
#include "MyString.h"
#define BUFFER_SIZE 1024
#define BUFFER2_SIZE 100
class Parallel;
class Collector;
class Process;
enum AcceptStage {
ACCEPT_STAGE_RECV_COMMAND = 1,
ACCEPT_STAGE_EXIT_COMMAND = 2,
ACCEPT_STAGE_LIST_COMMAND = 3,
ACCEPT_STAGE_ADD_COMMAND = 4,
ACCEPT_STAGE_ENABLE_COMMAND = 5,
ACCEPT_STAGE_REMOVE_COMMAND = 6,
ACCEPT_STAGE_WAIT_COMMAND = 7,
ACCEPT_STAGE_LIST_HOSTS = 8,
ACCEPT_STAGE_LIST_PROCESSES = 9,
ACCEPT_STAGE_LIST_COLLECTORS = 10,
ACCEPT_STAGE_LIST_RANGES = 11,
ACCEPT_STAGE_ADD_HOST = 12,
ACCEPT_STAGE_ADD_COLLECTOR = 13,
ACCEPT_STAGE_ADD_HOST_NUMBER = 14,
ACCEPT_STAGE_REMOVE_COLLECTOR = 15,
ACCEPT_STAGE_ENABLE_PROCESS = 16,
ACCEPT_STAGE_ENABLE_PROCESS_NUMBER = 17,
ACCEPT_STAGE_WAIT_HOST = 18,
ACCEPT_STAGE_WAIT_HOST_ENABLED = 19,
ACCEPT_STAGE_WAIT_HOST_ENABLED_NUMBER = 20,
ACCEPT_STAGE_WAIT_COLLECTOR = 21,
ACCEPT_STAGE_WAIT_COLLECTOR_DONE = 22,
ACCEPT_STAGE_WAIT_COLLECTOR_DONE_OUT = 23,
};
class AcceptHandler : public ReadHandler {
// friend classes & functions
// class methods
public:
static void call_callback(int pid, const MyString& message);
// members
private:
Parallel* p_manager;
int p_pid;
FILE* p_stdinput;
int p_writefd;
FILE* p_stdoutput;
char p_buffer[BUFFER_SIZE];
char p_buffer2[BUFFER2_SIZE];
AcceptStage p_accept_stage;
bool p_ca_parallel_is_waiting;
Collector* p_collector;
// private tools
private:
bool p_receive();
void p_get_output_filename(MyString& output_filename);
// constructors & the destructor
public:
AcceptHandler(Parallel* manager, int pid);
virtual ~AcceptHandler();
// comparators
// member accessing methods
protected:
virtual ReadHandlerResult call();
};
#endif /* __ACCEPTHANDLER_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Interactive.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __INTERACTIVE_H__
#define __INTERACTIVE_H__
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "Config.h"
#include "Object.h"
#include "Radius.h"
#include "Posture.h"
#include "Center.h"
#include "Normal.h"
class Interactives;
enum LocationForceType {
LOCATION_FORCE_TYPE_ATTRACTIVE = 1,
LOCATION_FORCE_TYPE_REPULSIVE = 2,
};
enum NormalForceType {
NORMAL_FORCE_TYPE_PARALLELIZE = 3,
NORMAL_FORCE_TYPE_DIRECTION_ARRANGEMENT = 4,
NORMAL_FORCE_TYPE_OUTSIDE_ARRANGEMENT = 5,
};
enum OriginalForceType {
ORIGINAL_FORCE_TYPE_ORIGINAL = 6,
};
class Interactive : public Object {
// friend classes & functions
// members
protected:
Radius p_radius;
Posture p_posture;
Center p_center;
Normal p_normal;
private:
bool p_done;
// private tools
private:
static Vector3 s_attractive_force(const Vector3& you, const Vector3& me, double delta);
static Vector3 s_repulsive_force(const Vector3& you, const Vector3& me, double delta);
// attributes
protected:
virtual Vector3 p_get_vertex_location(int index) const = 0;
void p_interaction_at(const Vector3& my_point_location,
const Vector3& by_your_location,
LocationForceType force_type, double delta);
// constructors & the destructor
public:
Interactive(Interactives* interactives, int sequence_no, double radius_length);
virtual ~Interactive();
Interactive& operator = (const Interactive& you); /* dont use */
// interactions
public:
void fix_radius_length(double fixed_length);
void fix_posture(const Matrix3& fixed_posture);
void fix_center_location(const Vector3& fixed_location);
void move_center_location(const Vector3& movement);
virtual void reset_interaction();
void interaction_at_center(const Vector3& by_your_location,
LocationForceType force_type, double delta);
void interaction_at_vertex(int index, const Vector3& by_your_location,
LocationForceType force_type, double delta);
void interaction_at_nearest_point(const Vector3& by_your_location,
LocationForceType force_type, double delta);
void interaction_to_normal_by_normal(const Vector3& your_normal,
NormalForceType force_type,
double delta);
void interaction_to_normal_by_location(const Vector3& your_location,
double delta);
virtual void interaction_original(OriginalForceType force_type,
Interactives* interactives, double delta);
void operate_interactions(int &stability, const Vector3& center);
void randomized_force(double width = 1.0);
void move_by(const Vector3& a);
// determining normal vector
public:
void reset_clockwise() { p_normal.clockwise = 0; }
int get_clockwise() const { return p_normal.clockwise; }
void reset_done() { p_done = false; }
bool get_done() const { return p_done; }
void set_done() { p_done = true; }
// I/O
public:
virtual void draw_opaque_by_OpenGL(bool selection) const;
virtual void draw_semitransparent_by_OpenGL(bool selection, bool frontface) const;
void memory_shape(FILE* archive) const;
void recall_shape(FILE* archive);
// member accessing methods
// attributes
public:
virtual int number_of_vertices() const = 0;
double get_radius_length() const { return p_radius.length; }
virtual Vector3 get_center_location() const { return p_center.location; }
Vector3 get_vertex_location(int index) const;
virtual Vector3 get_nearest_point(const Vector3& by_your_location) const = 0;
virtual Vector3 get_normal() const;
virtual Vector3 get_normal(const Vector3& by_your_location) const;
};
#endif /* __INTERACTIVE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/DistanceVector.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __DISTANCEVECTOR_H__
#define __DISTANCEVECTOR_H__
#include "Object.h"
class DistanceVector : public Object {
// friend classes & functions
// members
private:
int p_distances[12];
// private tools
// constructors & the destructor
public:
DistanceVector();
DistanceVector(const DistanceVector& you);
~DistanceVector();
DistanceVector& operator = (const DistanceVector& you);
// type converters
// comparators
public:
int compare(const DistanceVector* you) const;
bool operator == (const DistanceVector& you) const
{ return (compare(&you) == 0); }
// math operators
// I/O
public:
void print() const;
// class decision
// member accessing methods
public:
void append(int distance);
int operator [] (int index) const;
};
#endif /* __DISTANCEVECTOR_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/BoundaryCarbons.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __BOUNDARYCARBONS_H__
#define __BOUNDARYCARBONS_H__
#include "Set.h"
#include "Carbon.h"
class BoundaryCarbons {
// friend classes & functions
// members
private:
Set<Carbon> p_two_rings_carbons;
Set<Carbon> p_one_ring_carbons;
// private tools
// constructors & the destructor
public:
BoundaryCarbons();
void copy_from(const CarbonAllotrope* ca, const BoundaryCarbons& you);
~BoundaryCarbons();
BoundaryCarbons& operator = (const BoundaryCarbons& you); /* dont use */
// comparators
// I/O
// member accessing methods
// attributes
public:
int length() const
{ return p_one_ring_carbons.length() + p_two_rings_carbons.length(); }
void clean();
void add(Carbon* carbon);
int number_of_two_rings_carbons() const { return p_two_rings_carbons.length(); }
Carbon* get_two_rings_carbon_of_minimum_sequence_no() const;
void glow_to_one_ring_carbon(Carbon* carbon);
void glow_to_two_rings_carbon(Carbon* carbon);
void glow_to_three_rings_carbon(Carbon* carbon);
};
#endif /* __BOUNDARYCARBONS_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Qt/TreeModel.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __TREEMODEL_H__
#define __TREEMODEL_H__
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
class TreeItem;
class TreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit TreeModel(QObject *parent = 0);
~TreeModel();
QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
private:
void setupModelData(const QStringList &lines, TreeItem *parent);
TreeItem *rootItem;
};
#endif /* __TREEMODEL_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Interactives.h
|
<filename>src/Interactives.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __INTERACTIVES_H__
#define __INTERACTIVES_H__
#include "Object.h"
#include "List.h"
#include "InteractiveOperation.h"
#include "Interactive.h"
enum ActionLocation {
ACTION_LOCATION_CENTER = -1,
ACTION_LOCATION_NEAREST = -2,
ACTION_LOCATION_VERTEX = 0,
};
#define STABILITY_THRESHOLD 100
class Interactives : public Object {
// friend classes & functions
// members
public:
static bool s_need_simulation;
static bool s_need_draw_pentagon_cellophanes;
private:
List<InteractiveOperation> p_operations;
List<Interactive> p_interactives;
int p_simulation_active;
// private tools
private:
void p_calculate_interaction(LocationForceType force_type, double delta,
Interactive* one, int one_index,
Interactive* the_other, int the_other_index);
void p_calculate_interaction(NormalForceType force_type, double delta,
Interactive* one, Interactive* the_other);
// constructors & the destructor
public:
Interactives();
virtual ~Interactives();
Interactives& operator = (const Interactives& you); /* dont use */
// interactions
protected:
virtual void p_reset_interaction() = 0;
void p_register_interaction(LocationForceType force_type,
Interactive* one, int one_index,
Interactive* the_other, int the_other_index);
void p_register_interaction(NormalForceType force_type,
Interactive* one, Interactive* the_other);
void p_register_interaction(OriginalForceType force_type, Interactive* one);
public:
virtual const Vector3& get_center_location() const = 0;
void register_interactive(Interactive* interactive);
bool operate_interactions(double delta);
void randomized_force(double width = 1.0);
// I/O
public:
void draw_by_OpenGL(bool selection) const;
// stability
void resume_simulation() { p_simulation_active = STABILITY_THRESHOLD; }
// member accessing methods
};
#endif /* __INTERACTIVES_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Generator.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __GENERATOR_H__
#define __GENERATOR_H__
#include "Object.h"
#include "MyString.h"
enum GeneratorType {
GENERATOR_TYPE_SYMMETRIC = 1,
GENERATOR_TYPE_TUBE = 2,
GENERATOR_TYPE_ORDINARY = 3,
GENERATOR_TYPE_ILLEGAL = 4,
};
enum GeneratorState {
GENERATOR_STATE_START_SPECIFIED = 1,
GENERATOR_STATE_START_FROM_MINIMUM = 2,
GENERATOR_STATE_RUNNING = 3,
};
class Generator : public Object {
// friend classes & functions
// members
private:
GeneratorType p_type;
int p_scrap_no;
int p_n;
int p_m;
int p_h;
int p_minimum_polygons;
int p_maximum_vertices_of_polygons;
GeneratorState p_state;
int p_history_length;
int p_history_offset;
MyString p_history;
// private tools
private:
void p_glow(int value);
// constructors & the destructor
public:
Generator(bool symmetric = true, int maximum_vertices_of_polygons = 6);
Generator(int n, int m, int h, int maximum_vertices_of_polygons = 6);
Generator(const char* generator_formula, int maximum_vertices_of_polygons = 6);
Generator(const Generator& you);
Generator& operator = (const Generator& you);
~Generator();
// I/O
public:
void print_detail() const;
void print_progress(int length) const;
// member accessing methods
public:
GeneratorType type() const { return p_type; }
int scrap_no() const { return p_scrap_no; }
int n() const { return p_n; }
int m() const { return p_m; }
int h() const { return p_h; }
int glow_step();
int history();
bool is_there_next_branch() const;
void next_branch();
bool next_tree();
bool next_by_rollback();
void initialize_next_sequences();
void get_generator_formula(MyString& buffer, bool compress = true) const;
};
#endif /* __GENERATOR_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/InteractiveLine.h
|
<filename>src/InteractiveLine.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __INTERACTIVELINE_H__
#define __INTERACTIVELINE_H__
#include "Interactive.h"
class InteractiveLine : public Interactive {
// friend classes & functions
// members
// private tools
// attributes
protected:
virtual Vector3 p_get_vertex_location(int index) const;
// constructors & the destructor
public:
InteractiveLine(Interactives* interactives, int sequence_no);
virtual ~InteractiveLine();
InteractiveLine& operator = (const InteractiveLine& you); /* dont use */
// interactions
// representation
// I/O
// class decision
// member accessing methods
// attributes
public:
virtual int number_of_vertices() const;
virtual Vector3 get_nearest_point(const Vector3& by_your_location) const;
};
#endif /* __INTERACTIVELINE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/ReadHandler.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __READHANDLER_H__
#define __READHANDLER_H__
#include "Object.h"
enum ReadHandlerResult {
READ_HANDLER_RESULT_CONTINUED = 0,
READ_HANDLER_RESULT_TERMINATE = -1,
READ_HANDLER_RESULT_SCHEDULE = -2,
READ_HANDLER_RESULT_SCHEDULE_FORCE = -3,
READ_HANDLER_RESULT_SCHEDULE_AND_TERMINATE = -4,
READ_HANDLER_RESULT_TIMEOUT = -5,
READ_HANDLER_RESULT_EXIT = -6,
};
class ReadHandler : public Object {
// friend classes & functions
friend class ReadSelector;
// members
protected:
int p_readfd;
// constructors & the destructor
public:
ReadHandler();
virtual ~ReadHandler();
// comparators
public:
int compare(const ReadHandler* you) const;
// member accessing methods
public:
virtual bool is_listen_handler() const { return false; }
protected:
virtual ReadHandlerResult call();
};
#endif /* __READHANDLER_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/AvoidBugs.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __AVOIDBUGS_H__
#define __AVOIDBUGS_H__
#define AVOID_GLLIGHTMODEL_BUG_IN_WGL 1 // TODO 008
#endif /* __AVOIDBUGS_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Parallel.h
|
<filename>src/Parallel.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __PARALLEL_H__
#define __PARALLEL_H__
#include "Set.h"
#include "List.h"
#include "Host.h"
#include "Process.h"
#include "Collector.h"
#include "MyString.h"
class ReadSelector;
class ReadHandler;
class Parallel {
// friend classes & functions
// members
private:
MyString p_client_cwd;
MyString p_server_pipe_name;
MyString p_server_lockfile_name;
MyString p_server_logfile_name;
MyString p_client_pipe_base;
Set<Host> p_hosts;
Set<Process> p_processes;
Set<Process> p_unassigned_processes;
List<Collector> p_collectors;
ReadSelector* p_selector;
// private tools
private:
AssignProcessResult p_assign_process(Process* process, bool force = true);
void p_enable_processes(Host* searched_host, int from, int to);
void p_disable_processes(Host* searched_host, int from, int to);
// constructors & the destructor
public:
Parallel(const MyString& home);
~Parallel();
// scheduling
public:
bool assign_processes(bool force = true);
void manage_unassigned_process(Process* process);
// I/O
public:
bool join(ReadHandler* rhandler);
void command_loop();
void print_hosts(FILE* output) const;
bool print_ranges(FILE* output, int index) const;
bool print_ranges(FILE* output, Collector* collector) const;
bool print_processes(FILE* output, int host_index);
void print_processes(FILE* output);
void print_collectors(FILE* output, bool ranges_too) const;
// member accessing methods
public:
void set_client_cwd(const char* client_cwd);
const char* get_client_cwd() const { return p_client_cwd; }
bool add_host(const char* host_name, int process_num);
bool remove_host(const char* host_name);
Host* search_host(const char* host_name);
const Set<Host>& get_hosts() const { return p_hosts; }
bool enable_processes(const char* host_name, int number);
void disable_all_processes();
Process* search_process(Host* host, int process_id);
const Set<Process>& get_processes() const { return p_processes; }
bool add_collector(Collector* collector);
int search_collector(const char* output_filename);
bool remove_collector(int index);
bool remove_collector(const char* output_filename);
const List<Collector>& get_collectors() const { return p_collectors; }
const char* get_server_pipe_name() const { return p_server_pipe_name; }
const char* get_client_pipe_base() const { return p_client_pipe_base; }
};
#endif /* __PARALLEL_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Queue.h
|
<filename>src/Queue.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include <assert.h>
#include "DebugMemory.h"
#define QUEUE_IMPL_CONTAINER_SIZE 10
// implementation inner classes
template <class T> class QueueImpl {
// members
public:
QueueImpl<T>* p_next;
T* p_container[QUEUE_IMPL_CONTAINER_SIZE];
// constructors & the destructor
public:
QueueImpl() : p_next(0) { }
~QueueImpl() { }
QueueImpl<T>& operator = (const QueueImpl<T>& you); /* dont use */
};
template <class T> class Queue {
// friend classes & functions
// members
protected:
QueueImpl<T>* p_top;
QueueImpl<T>* p_bottom;
int p_length;
int p_enq_offset_in_bottom;
int p_deq_offset_in_top;
// protected tools
// constructors & the destructor
public:
Queue() : p_top(new QueueImpl<T>()), p_length(0),
p_enq_offset_in_bottom(0), p_deq_offset_in_top(0) { p_bottom = p_top; }
~Queue() { clean(); delete p_top; }
Queue<T>& operator = (const Queue<T>& you); /* dont use */
// type converters
// comparators
// math operators
// I/O
// class decision
// member accessing methods
public:
void enqueue(T* element)
{
element->link_up();
p_bottom->p_container[p_enq_offset_in_bottom++] = element;
if (p_enq_offset_in_bottom == QUEUE_IMPL_CONTAINER_SIZE)
{
p_bottom->p_next = new QueueImpl<T>();
p_bottom = p_bottom->p_next;
p_enq_offset_in_bottom = 0;
}
++p_length;
}
T* dequeue()
{
if (p_length == 0)
return 0;
--p_length;
T* element = p_top->p_container[p_deq_offset_in_top++];
element->link_down();
if (p_deq_offset_in_top == QUEUE_IMPL_CONTAINER_SIZE)
{
if (p_top->p_next == 0)
{
assert(p_length == 0);
p_enq_offset_in_bottom = 0;
p_deq_offset_in_top = 0;
}
else
{
QueueImpl<T>* work = p_top;
p_top = p_top->p_next;
delete work;
p_deq_offset_in_top = 0;
}
}
return element;
}
void clean() { while (dequeue()) /* do nothing */; }
int length() const { return p_length; }
};
#endif
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/PddGfLine.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __PDDGFLINE_H__
#define __PDDGFLINE_H__
#include "Object.h"
#include "MyString.h"
class Fullerene;
class PddGfLine : public Object {
// friend classes & functions
// members
private:
int p_number_of_carbons;
int p_number_of_automorphisms;
bool p_mirror_symmetric;
MyString p_characteristic;
MyString p_generator_formula;
// private tools
// constructors & the destructor
public:
PddGfLine(Fullerene* fullerene, bool with_pdd);
~PddGfLine();
// comparators
// I/O
// member accessing methods
public:
int get_number_of_carbons() const { return p_number_of_carbons; }
int get_number_of_automorphisms() const { return p_number_of_automorphisms; }
void set_mirror_symmetric() { p_mirror_symmetric = true; }
bool get_mirror_symmetric() const { return p_mirror_symmetric; }
const char* get_characteristic() const { return (char*)p_characteristic; }
const char* get_generator_formula() const { return (char*)p_generator_formula; }
};
#endif /* __PDDGFLINE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Set.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __SET_H__
#define __SET_H__
#include "List.h"
template <class T> class Set : public List<T> {
// friend classes & functions
// members
// private tools
private:
bool p_search(const T* element, int& result_index)
{
List<T>::p_make_room();
int min = -1;
int max = List<T>::p_length;
while (min + 1 < max)
{
int mid = (min + max) / 2;
int cmp = element->compare(List<T>::p_container[mid]);
if (cmp == 0)
{
result_index = mid;
return true;
}
if (cmp > 0)
min = mid;
else
max = mid;
}
result_index = max;
return false;
}
// constructors & the destructor
public:
Set() : List<T>() { }
Set(const Set<T>& you) : List<T>()
{
List<T>::add(you);
}
~Set() { }
Set<T>& operator = (const Set<T>& you)
{
if (this != &you)
{
List<T>::p_clean();
List<T>::add(you);
}
return *this;
}
// I/O
// member accessing methods
public:
T* search(const T* element)
{
int result_index;
if (p_search(element, result_index))
return List<T>::p_container[result_index];
return 0;
}
T* search_else_add(T* element)
{
int result_index;
if (p_search(element, result_index))
return List<T>::p_container[result_index];
for (int i = List<T>::p_length; i > result_index; --i)
List<T>::p_container[i] = List<T>::p_container[i - 1];
List<T>::p_length++;
element->link_up();
List<T>::p_container[result_index] = element;
return 0;
}
bool remove(T* element)
{
int result_index;
if (!p_search(element, result_index))
return false;
--List<T>::p_length;
element = List<T>::p_container[result_index];
for ( ; result_index < List<T>::p_length; ++result_index)
List<T>::p_container[result_index] = List<T>::p_container[result_index + 1];
element->link_down();
return true;
}
};
#endif
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/SymmetryAxisNormal.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __SYMMETRYAXISNORMAL_H__
#define __SYMMETRYAXISNORMAL_H__
#include <stdio.h>
#include "InteractiveRegularPolygon.h"
#include "CarbonAllotrope.h"
class SymmetryAxisNormal : public InteractiveRegularPolygon {
// friend classes & functions
// members
private:
CarbonAllotrope* p_ca;
SymmetryAxis* p_axis;
// private tools
private:
// constructors & the destructor
public:
SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis);
virtual ~SymmetryAxisNormal();
Bond& operator = (const SymmetryAxisNormal& you); /* dont use */
// interactions
public:
virtual void reset_interaction();
virtual void interaction_original(OriginalForceType force_type,
Interactives* interactives, double delta);
// I/O
public:
virtual void draw_opaque_by_OpenGL(bool selection) const;
// member accessing methods
};
#endif /* __SYMMETRYAXISNORMAL_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Stack.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __STACK_H__
#define __STACK_H__
#include "List.h"
template <class T> class Stack : public List<T> {
// friend classes & functions
// members
// private tools
// constructors & the destructor
public:
Stack() : List<T>() { }
Stack(const Stack<T>& you) : List<T>()
{
List<T>::add(you);
}
~Stack() { }
Stack<T>& operator = (const Stack<T>& you)
{
if (this != &you)
{
List<T>::p_clean();
List<T>::add(you);
}
return *this;
}
// type converters
// comparators
// math operators
// I/O
// class decision
// member accessing methods
public:
void push(T* element)
{
List<T>::add(element);
}
T* pop()
{
if (List<T>::p_length == 0)
return 0;
return List<T>::remove(List<T>::p_length - 1);
}
T* refer_top()
{
if (List<T>::p_length == 0)
return 0;
return List<T>::operator [] (List<T>::p_length - 1);
}
};
#endif
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Host.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __HOST_H__
#define __HOST_H__
#include <stdio.h>
#include "Object.h"
#include "MyString.h"
#include "List.h"
#include "ObjectInt2.h"
class Host : public Object {
// friend classes & functions
// members
private:
MyString p_host_name;
int p_number_of_processes;
int p_number_of_enabled_processes;
List<ObjectInt2> p_enable_waiters;
// private tools
private:
void p_search_and_call_enable_waiters(int num);
// constructors & the destructor
public:
Host(const char* host_name, int number_of_processes);
~Host();
// comparators
public:
int compare(const Host* you) const;
// I/O
public:
void print(FILE* output) const;
// member accessing methods
public:
const char* get_host_name() const { return p_host_name; }
int number_of_processes() const { return p_number_of_processes; }
int number_of_enabled_processes() const { return p_number_of_enabled_processes; }
bool enable_processes(int num);
void enter_enabled_waiter(int num, int pid);
};
#endif /* __HOST_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/ReadKqueue.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __READKQUEUE_H__
#define __READKQUEUE_H__
#include "ReadSelector.h"
class ReadKqueue : public ReadSelector {
// friend classes & functions
// members
// private tools
// constructors & the destructor
public:
ReadKqueue();
~ReadKqueue();
// member accessing methods
public:
virtual bool join(ReadHandler* handler);
virtual bool defect(ReadHandler* handler);
virtual ReadHandlerResult select(int timeout);
};
#endif /* __READKQUEUE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Config.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CONFIG_H__
#define __CONFIG_H__
/* ca-modeling の POVRay アニメーションで法線を表示する。 */
// #define CONFIG_DRAW_NORMAL_VECTOR_IN_POVRAY_ANIMATION 1
/* FullereneViewer の POVRay 6面展開図で法線を表示する。 */
// #define CONFIG_DRAW_NORMAL_VECTOR_IN_POVRAY_SIX_VIEWS 1
/* FullereneViewer のぐるぐるモードで法線を表示する。 */
// #define CONFIG_DRAW_NORMAL_VECTOR_IN_GURUGURU_MODE 1
/* FullereneViewer の POVRay スナップショットの背景を透明色にする。 */
// #define CONFIG_PAINT_TRANSPARENT_COLOR_TO_BACKGROUND_IN_POVRAY_SNAPSHOT 1
/* FullereneViewer のぐるぐるモードでの目標CPU使用率(単位は%)を設定する。 */
/* 値は 1 から 99 までの整数値 */
#define CONFIG_VIEWER_CPU_USAGE_TARGET_RATE 80
/* 以下のマクロ定義を有効化すると、 */
/* ca-generator の対称フラーレン生成は、五員環への距離を元に次の生成箇所を決定する。 */
// #define CONFIG_SYMMETRIC_GENERATOR_DECIDES_NEXT_FILL_POINT_BY_DISTANCES_TO_PENTAGON 1
/* scrap_order を元に次の生成箇所を決定する場合は上記マクロをコメントアウトする。 */
#endif /* __CONFIG_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/List.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __LIST_H__
#define __LIST_H__
#include "DebugMemory.h"
template <class T> class List {
// friend classes & functions
// members
protected:
int p_container_size;
int p_length;
T** p_container;
// protected tools
protected:
void p_make_room()
{
if (p_length == p_container_size)
{
p_container_size *= 2;
T** new_ptr = new T*[p_container_size];
for (int i = 0; i < p_length; ++i)
new_ptr[i] = p_container[i];
delete[] p_container;
p_container = new_ptr;
}
}
void p_clean()
{
for (int i = 0; i < p_length; ++i)
p_container[i]->link_down();
p_length = 0;
}
// constructors & the destructor
public:
List() : p_container_size(16), p_length(0), p_container(new T*[p_container_size]) { }
List(const List<T>& you) : p_container_size(16), p_length(0),
p_container(new T*[p_container_size])
{
add(you);
}
~List() { p_clean(); delete[] p_container; }
List<T>& operator = (const List<T>& you)
{
if (this != &you)
{
p_clean();
add(you);
}
return *this;
}
// type converters
// comparators
// math operators
// I/O
// class decision
// member accessing methods
public:
void add(T* element)
{
p_make_room();
element->link_up();
p_container[p_length++] = element;
}
void add(const List<T>& you)
{
int len = you.length();
for (int i = 0; i < len; ++i)
add(you[i]);
}
void remove(T* element)
{
for (int i = 0; i < p_length; ++i)
{
if (p_container[i] == element)
{
(void)remove(i);
return;
}
}
}
T* remove(int offset)
{
if ((offset < 0) || (p_length <= offset))
return 0;
--p_length;
T* element = p_container[offset];
for ( ; offset < p_length; ++offset)
p_container[offset] = p_container[offset + 1];
element->link_down();
return element;
}
void clean() { p_clean(); }
int length() const { return p_length; }
T* operator[](int offset) const
{
if ((offset < 0) || (p_length <= offset))
return 0;
return p_container[offset];
}
};
#endif
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Qt/AboutWindow.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __ABOUTWINDOW_H__
#define __ABOUTWINDOW_H__
#include <QMainWindow>
namespace Ui {
class AboutWindow;
}
class AboutWindow : public QMainWindow
{
Q_OBJECT
public:
explicit AboutWindow(QWidget *parent = 0);
~AboutWindow();
static void showAbout();
protected:
virtual void closeEvent(QCloseEvent *);
protected:
void paintEvent(QPaintEvent *);
private:
Ui::AboutWindow *ui;
};
#endif /* __ABOUTWINDOW_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Version.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __VERSION_H__
#define __VERSION_H__
#include <stdio.h>
#define FULLERENE_VIEWER_VERSION "1.4.1"
extern void print_version(const char* program_name, FILE* output = 0);
#endif /* __VERSION_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/ObjectString.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __OBJECTSTRING_H__
#define __OBJECTSTRING_H__
#include "Object.h"
#include "MyString.h"
class ObjectString : public Object, MyString {
// friend classes & functions
// members
// private tools
// constructors & the destructor
public:
ObjectString();
ObjectString(const char* value);
ObjectString(const ObjectString& you);
#if 0
ObjectString& operator = (const char* value);
ObjectString& operator = (const ObjectString& you);
#endif
~ObjectString();
// comparators
public:
int compare(const ObjectString* you) const
{ return MyString::compare((const MyString*)you); }
// I/O
// member accessing methods
public:
operator char*() const { return MyString::operator char*(); }
};
#endif /* __OBJECTSTRING_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/MyString.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __MYSTRING_H__
#define __MYSTRING_H__
class MyString {
/* 実装は必ず領域を作る。*/
/* 途中にヌル文字があってもよい。*/
/* 常にヌルターミネートしているので、途中にヌル文字がなければ文字列として扱える。*/
/* p_glow_to() と p_glow_and_copy() がヌルターミネートしていることを保証する。*/
// friend classes & functions
// members
private:
int p_buffer_size;
int p_length;
char* p_buffer;
// private tools
private:
void p_init_to(int length);
void p_glow_to(int length);
void p_round_up_buffer_size();
// constructors & the destructor
public:
MyString();
MyString(const char* value);
MyString(const MyString& you);
MyString& operator = (const char* value);
MyString& operator = (const MyString& you);
~MyString();
// comparators
public:
int compare(const char* you) const;
int compare(const MyString* you) const;
// I/O
// member accessing methods
public:
void set_value(const char* value);
void set_value(const char* value, int length);
int length() const { return p_length; }
operator char*() const { return p_buffer; }
char& operator [](int index);
void set_char_at(int index, char value);
void resize(int new_length);
void append_char(char appendant);
void append_string(const char* appendant);
void append_int(int appendant);
};
#endif /* __MYSTRING_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/MinimumRepresentation.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __MINIMUMREPRESENTATION_H__
#define __MINIMUMREPRESENTATION_H__
#include "Object.h"
#include "MyString.h"
class Fullerene;
class MinimumRepresentation : public Object {
// friend classes & functions
// members
private:
MyString p_repres;
// private tools
// constructors & the destructor
public:
MinimumRepresentation(const Fullerene* fullerene);
virtual ~MinimumRepresentation();
MinimumRepresentation& operator = (const MinimumRepresentation& you); /* dont use */
// comparators
public:
int compare(const MinimumRepresentation* you) const;
// I/O
public:
void print() const;
// member accessing methods
};
#endif /* __REPRESENTATION_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Quaternion.h
|
<reponame>maruinen/FullereneViewer<filename>src/Quaternion.h
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __QUATERNION_H__
#define __QUATERNION_H__
class Vector3;
class Quaternion {
// friend classes & functions
friend class Matrix3;
// members
private:
double p_r, p_x, p_y, p_z;
// private tools
private:
void p_initialize_from_axis_and_degree(const Vector3& axis, double degree);
// constructors & the destructor
public:
Quaternion(double r, double x, double y, double z);
Quaternion(Vector3 from, Vector3 to);
Quaternion(const Vector3& you);
Quaternion(const Vector3& axis, double degree);
void operator = (const Quaternion& you);
~Quaternion();
// type converters
// comparators
// math operators
public:
friend Quaternion operator * (const Quaternion& a, const Quaternion& b);
friend Quaternion operator + (const Quaternion& a, const Quaternion& b);
friend Quaternion operator - (const Quaternion& a, const Quaternion& b);
Quaternion conjugation() const;
void normalize();
Vector3 operator () (const Vector3& a) const;
// V * Matrix3(Q) = Q(V)
// I/O
public:
void print_out() const;
// class decision
// member accessing methods
};
#endif /* __QUATERNION_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Automorphism.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __AUTOMORPHISM_H__
#define __AUTOMORPHISM_H__
#include "Object.h"
class Carbon;
class Bond;
class CarbonAllotrope;
class Automorphism : public Object {
// friend classes & functions
// members
private:
CarbonAllotrope* p_ca;
int p_index;
int p_order;
int* p_carbon_map;
int* p_bond_map;
int* p_ring_map;
int* p_boundary_map;
// private tools
// constructors & the destructor
public:
Automorphism(CarbonAllotrope* ca);
Automorphism(CarbonAllotrope* ca, Bond* from_bond, Carbon* from_carbon,
Bond* to_bond, Carbon* to_carbon);
void initialize(int from_seq, int to_seq);
virtual ~Automorphism();
Automorphism& operator = (const Automorphism& you); /* dont use */
// comparators
friend bool operator == (const Automorphism& one, const Automorphism& the_other);
friend bool operator != (const Automorphism& one, const Automorphism& the_other);
// math operators
public:
Automorphism* composition(const Automorphism* you) const;
Automorphism* inverse() const;
bool is_unit() const;
// I/O
public:
void print_out();
void print_orbit(Carbon* carbon);
// class decision
// member accessing methods
public:
int number_of_carbons() const;
int number_of_bonds() const;
int number_of_rings() const;
int number_of_boundaries() const;
CarbonAllotrope* get_carbon_allotrope() const { return p_ca; }
int operator () (int sequence_no) const;
int carbon_map(int sequence_no) const;
int bond_map(int sequence_no) const;
int ring_map(int sequence_no) const;
int boundary_map(int sequence_no) const;
void set_step(int sequence_no);
int order();
int fixed_carbons(int& sequence_no0, int& sequence_no1);
int fixed_bonds(int& sequence_no0, int& sequence_no1);
int fixed_rings(int& sequence_no0, int& sequence_no1);
int fixed_boundaries(int& sequence_no0, int& sequence_no1);
};
inline bool operator != (const Automorphism& one, const Automorphism& the_other)
{
return !(one == the_other);
}
#endif /* __AUTOMORPHISM_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Collector.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __COLLECTOR_H__
#define __COLLECTOR_H__
#include "Object.h"
#include "MyString.h"
#include "ObjectString.h"
#include "ObjectInt.h"
#include "Set.h"
#include "List.h"
#include "Range.h"
#include "Process.h"
class Collector : public Object {
// friend classes & functions
// members
private:
List<ObjectString> p_options;
List<ObjectString> p_formula_segments;
MyString p_output_filename;
Set<Range> p_ranges;
int p_number;
int p_outfd;
List<ObjectInt> p_done_waiters;
// private tools
// constructors & the destructor
public:
Collector();
~Collector();
// scheduling
public:
AssignProcessResult assign_process(Process* process, bool force = true);
// comparators
public:
int compare(const Collector* you) const;
// I/O
public:
void print(FILE* output) const;
bool collect(const char* line, int length);
// member accessing methods
public:
void add_option(const char* option);
bool add_formula_segment(const char* start_formula);
bool setup_formula_segments();
void add_output_filename(const char* output_filename);
bool setup_output_file();
const List<ObjectString>& get_options() const { return p_options; }
const List<ObjectString>& get_formula_segments() const { return p_formula_segments; }
const char* get_output_filename() const { return p_output_filename; }
double get_progress(bool& done) const;
double get_elapsed_sec() const;
void add_range(Range* range);
int number_of_ranges() const { return p_ranges.length(); }
const Range* get_range(int index) const;
void enter_done_waiter(int pid);
void check_done_and_call_done_waiters();
};
#endif /* __COLLECTOR_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/ObjectInt2.h
|
<reponame>maruinen/FullereneViewer
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __OBJECTINT2_H__
#define __OBJECTINT2_H__
#include "Object.h"
class ObjectInt2 : public Object {
// friend classes & functions
// members
private:
int p_key;
int p_value;
// private tools
// constructors & the destructor
public:
ObjectInt2() : p_key(0), p_value(0) { }
ObjectInt2(int key, int value) : p_key(key), p_value(value) { }
ObjectInt2(const ObjectInt2& you) : p_key(you.p_key), p_value(you.p_value) { }
~ObjectInt2() { }
// comparators
public:
int compare(const ObjectInt2* you) const { return p_key - you->p_key; }
// I/O
// member accessing methods
public:
int get_key() const { return p_key; }
int get_value() const { return p_value; }
};
#endif /* __OBJECTINT2_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Characteristic.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CHARACTERISTIC_H__
#define __CHARACTERISTIC_H__
#include <stdio.h>
#include "DistanceVector.h"
#include "Set.h"
#include "Object.h"
class CarbonAllotrope;
class Characteristic : public Object {
// friend classes & functions
// members
private:
Set<DistanceVector> p_dvs;
// private tools
// constructors & the destructor
public:
Characteristic(CarbonAllotrope* ca);
~Characteristic();
Characteristic& operator = (const Characteristic& you); /* dont use */
// type converters
// comparators
// math operators
// I/O
public:
void print_detail() const;
const char* get_summary() const;
void print_summary(FILE* fptr = stdout) const;
// class decision
// member accessing methods
public:
int number_of_distance_vector() const { return p_dvs.length(); }
void add(DistanceVector* dv) { p_dvs.add(dv); }
DistanceVector* get_distance_vector(int index);
};
#endif /* __CHARACTERISTIC_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/CarbonAllotrope.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CARBONALLOTROPE_H__
#define __CARBONALLOTROPE_H__
#include <stdio.h>
#include "Interactives.h"
#include "List.h"
#include "Ring.h"
#include "Carbon.h"
#include "Bond.h"
#include "ConnectedBoundary.h"
#include "SymmetryAxis.h"
#include "MyString.h"
class Representations;
class Pattern;
class BoundaryCarbons;
class CarbonAllotrope : public Interactives {
// friend classes & functions
// members
public:
static bool s_need_representations;
static bool s_need_representations_reflection;
static bool s_need_all_axes;
static bool s_need_major_axes;
static bool s_need_principal_component_axes;
private:
List<Ring> p_rings;
List<Carbon> p_carbons;
int p_scrap_no;
int p_scrap_order;
List<Carbon> p_centers;
List<Bond> p_bonds;
List<ConnectedBoundary> p_boundaries;
bool p_has_reflection_symmetricity;
List<SymmetryAxis> p_axes;
Vector3 p_center_location;
double p_Eigenvalue1, p_Eigenvalue2, p_Eigenvalue3;
Vector3 p_Eigenvector1, p_Eigenvector2, p_Eigenvector3;
public:
int ring_next_sequence;
int carbon_next_sequence;
double carbon_radius;
int carbon_color;
int bond_next_sequence;
double bond_radius;
int bond_color;
int boundary_next_sequence;
bool print_out_sequence_no;
// private tools
private:
void p_make_n_polygon(int n_members);
void p_set_center();
void p_list_most_inside_carbons_on_boundary(List<Carbon>& boundary);
// constructors & the destructor
public:
CarbonAllotrope();
CarbonAllotrope* copy() const;
virtual ~CarbonAllotrope();
CarbonAllotrope& operator = (const CarbonAllotrope& you); /* dont use */
void clean();
// general purpose constructions
private:
ErrorCode p_fill_hexagons_around(Ring* ring);
public:
ErrorCode fill_hexagons_around_n_polygons(int n_members);
ErrorCode append_n_polygon_at_carbon(int n_members, int carbon_sequence_no);
ErrorCode append_n_polygon_at_carbons(int n_members, const int* carbon_sequence_nos);
ErrorCode append_n_polygon_at_bond(int n_members, int bond_sequence_no);
// fullerene constructions
private:
int p_calculate_period(const List<Carbon>& boundary, int& offset);
public:
ErrorCode enlarge_cylinder_by_n_polygons(Pattern* n_pattern, int& result_number);
ErrorCode make_fullerene(int distance);
ErrorCode
fill_n_polygons_around_carbons_closed_to_center_and_pentagons(int n_members,
int& number_of_results);
ErrorCode fill_n_polygon_around_carbon(int n_members, Carbon* carbon,
BoundaryCarbons& boundary);
ErrorCode make_symmetric_scrap(int scrap_no);
// carbon nano-tube constructions
private:
char* p_determine_permutation_of_lattice_basis(int n, int m);
void p_make_equator_by_chiral_characteristic(int n, int m);
public:
void make_equator_by_chiral_characteristic(int n, int m, int h);
void make_y_branch();
void close_force();
void close_normally_once();
// construction rollback
void rollback(int ring_next_sequence, int carbon_next_sequence, int bond_next_sequence);
// distance
private:
void p_calculate_distances_to_pentagons();
int p_maximum_distance_to_set();
public:
void calculate_distances_to_set(List<Carbon>& set);
void print_distances_between_pentagons();
// determining normal vector
public:
void set_clockwise(int clockwise);
void reset_done();
// interactions
protected:
virtual void p_reset_interaction();
public:
virtual const Vector3& get_center_location() const { return p_center_location; }
public:
void register_interactions();
// representation
private:
void p_all_representations_half(Representations* results, int clockwise);
public:
void all_representations(Representations* results);
// six-views drawing
public:
void reset_three_axes();
void calculate_three_axes();
void get_primary_Eigenvalue_and_Eigenvector(double& Eigenvalue,
Vector3& Eigenvector) const
{ Eigenvalue = p_Eigenvalue1; Eigenvector = p_Eigenvector1; }
void get_secondary_Eigenvalue_and_Eigenvector(double& Eigenvalue,
Vector3& Eigenvector) const
{ Eigenvalue = p_Eigenvalue2; Eigenvector = p_Eigenvector2; }
void get_tertiary_Eigenvalue_and_Eigenvector(double& Eigenvalue,
Vector3& Eigenvector) const
{ Eigenvalue = p_Eigenvalue3; Eigenvector = p_Eigenvector3; }
Matrix3 generate_matrix_of_six_views();
void get_range_of_six_views(const Matrix3& mosv,
Vector3& minimum, Vector3& maximum) const;
// mathematics
public:
int Euler_characteristic() const;
void count_carbons(int& number_of_carbons_with_one_ring,
int& number_of_carbons_with_two_rings,
int& number_of_carbons_with_three_rings) const;
// I/O
public:
void print_detail();
void print_boundary_representations();
void print_axes() const;
void print_axes_summary(FILE* fptr = stdout) const;
void draw_by_POVRay(const MyString& file_name_base, double delta, int steps,
int divisions);
void OpenGL_to_POVRay(const MyString& file_name_base, int view,
const Quaternion& rotation);
void draw_six_views_by_POVRay(const MyString& file_name_base);
static void execute_POVRay(const MyString& pov_name);
void draw_force_to_circle_by_POVRay(const MyString& file_name_base,
List<Carbon>& cutend_list,
double delta, int steps, int divisions);
void draw_force_to_circle_by_POVRay(const MyString& file_name_base,
double delta, int steps, int divisions);
void draw_development_view_by_POVRay(const MyString& file_name_base, Ring* cutend_ring,
double delta, int steps, int divisions);
void print_POVRay_scene_description(FILE* fptr) const;
void print_POVRay_scene_description(FILE* fptr, const Matrix3& rot, const Vector3& move,
bool clipped_by_Z_non_negative) const;
void memory_shape(const MyString& file_name_base) const;
void recall_shape(const MyString& file_name_base);
// member accessing methods
public:
// rings
int number_of_rings() const { return p_rings.length(); }
void register_ring(Ring* ring);
void remove_ring(Ring* ring);
Ring* get_ring(int index) const;
Ring* get_ring_by_sequence_no(int sequence_no) const;
// carbons
int number_of_carbons() const { return p_carbons.length(); }
void register_carbon(Carbon* ring);
Carbon* get_carbon(int index) const;
Carbon* get_carbon_by_sequence_no(int sequence_no) const;
// bonds
int number_of_bonds() const { return p_bonds.length(); }
void register_bond(Bond* ring);
Bond* get_bond(int index) const;
Bond* get_bond_by_sequence_no(int sequence_no) const;
// connected boundaries
// For temporary use in construction phase.
int list_oldest_connected_boundary(List<Carbon>& result) const;
int list_oldest_connected_boundary_carbons(BoundaryCarbons& result) const;
int list_oldest_connected_boundary(List<Carbon>& result,
const List<Carbon>& ignores) const;
int list_newborn_connected_boundary(List<Carbon>& result) const;
// CarbonAllotrope memories all boundaries after construction done.
void all_boundaries();
int number_of_boundaries() const { return p_boundaries.length(); }
void register_boundary(ConnectedBoundary* boundary);
ConnectedBoundary* get_boundary(int index) const;
ConnectedBoundary* get_boundary_by_sequence_no(int sequence_no) const;
// reflections symmetricity
void has_reflection_symmetricity(bool yes) { p_has_reflection_symmetricity = yes; }
bool has_reflection_symmetricity() const { return p_has_reflection_symmetricity; }
// axes
int number_of_axes() const { return p_axes.length(); }
SymmetryAxis* get_axis(int index) const;
void get_major_axes(List<SymmetryAxis>& result) const;
void register_axis(SymmetryAxis* axis);
};
#endif /* __CARBONALLOTROPE_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Qt/HelpBrowser.h
|
<reponame>maruinen/FullereneViewer<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __HELPBROWSER_H__
#define __HELPBROWSER_H__
#include <QtWidgets>
class QWebView;
QT_BEGIN_NAMESPACE
class QLineEdit;
QT_END_NAMESPACE
class HelpBrowser : public QMainWindow
{
Q_OBJECT
public:
HelpBrowser(const QUrl& url);
static void showHelp();
protected:
virtual void closeEvent(QCloseEvent *);
private:
QWebView *view;
};
#endif /* __HELPBROWSER_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/Configuration.h
|
<filename>src/Configuration.h<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CONFIGURATION_H__
#define __CONFIGURATION_H__
#include "MyString.h"
#define CONFIGURATION_FILE_NAME "/.FullereneViewer.conf"
#define WORKING_FOLDER_NAME "/fullerene"
#ifdef _WIN32
# define POVRAY_COMMAND_LINE "\"C:\\Program Files\\POV-Ray\\v3.7\\bin\\pvengine32-sse2.exe\" /RENDER +FN +UA %s /EXIT"
#elif defined(__APPLE__)
# define POVRAY_COMMAND_LINE "/usr/local/bin/povray -W1600 -H1200 +FN +UA %s"
#elif defined(__unix)
# define POVRAY_COMMAND_LINE "povray37 -W1600 -H1200 +FN +UA %s"
#else
# define POVRAY_COMMAND_LINE "bad command line"
#endif
enum Quality {
QUALITY_HIGH,
QUALITY_MIDDLE,
QUALITY_LOW
};
enum DisplaySymmetryAxes {
DISPLAY_ALL_SYMMETRY_AXES,
DISPLAY_MAJOR_SYMMETRY_AXES,
DISPLAY_NO_SYMMETRY_AXES
};
enum DisplayPrincipalComponentAxes {
DISPLAY_ALL_PRINCIPAL_COMPONENT_AXES,
DISPLAY_NO_PRINCIPAL_COMPONENT_AXES
};
enum DrawPentagonCellophanes {
DRAW_PENTAGON_STRONG_CELLOPHANES,
DRAW_PENTAGON_TINT_CELLOPHANES,
DRAW_PENTAGON_MONO_CHROME_CELLOPHANES,
DRAW_PENTAGON_TRANSPARENT
};
class Configuration {
// friend classes & functions
// members
private:
MyString p_configuration_file_name;
MyString p_working_folder_name;
MyString p_povray_command_line;
Quality p_picture_quality;
Quality p_motion_quality;
DisplaySymmetryAxes p_display_symmetry_axes;
DisplayPrincipalComponentAxes p_display_principal_component_axes;
DrawPentagonCellophanes p_draw_pentagon_cellophanes;
// private tools
// constructors & the destructor
public:
Configuration(const char* home, const char* desktop);
~Configuration();
// comparators
// I/O
void load();
void save() const;
void reflect() const;
// member accessing methods
Quality get_picture_quality() const { return p_picture_quality; }
void set_picture_quality(Quality quality) { p_picture_quality = quality; }
Quality get_motion_quality() const { return p_motion_quality; }
void set_motion_quality(Quality quality) { p_motion_quality = quality; }
DisplaySymmetryAxes get_display_symmetry_axes() const
{ return p_display_symmetry_axes; }
void set_display_symmetry_axes(DisplaySymmetryAxes display_symmetry_axes)
{ p_display_symmetry_axes = display_symmetry_axes; }
DisplayPrincipalComponentAxes get_display_principal_component_axes() const
{ return p_display_principal_component_axes; }
void set_display_principal_component_axes(DisplayPrincipalComponentAxes
display_principal_component_axes)
{ p_display_principal_component_axes = display_principal_component_axes; }
DrawPentagonCellophanes get_draw_pentagon_cellophanes() const
{ return p_draw_pentagon_cellophanes; }
void set_draw_pentagon_cellophanes(DrawPentagonCellophanes draw_pentagon_cellophanes)
{ p_draw_pentagon_cellophanes = draw_pentagon_cellophanes; }
const char* get_working_folder_name() const { return p_working_folder_name; }
void set_working_folder_name(const char* path);
const char* get_povray_command_line() const { return p_povray_command_line; }
void set_povray_command_line(const char* command_line);
};
extern Configuration *configuration;
#endif /* __CONFIGURATION_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
a-kolosov/PieChartView
|
ChartSDK/Supporting Files/ChartSDK.h
|
//
// ChartSDK.h
// ChartSDK
//
// Created by <NAME> on 12/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for ChartSDK.
FOUNDATION_EXPORT double ChartSDKVersionNumber;
//! Project version string for ChartSDK.
FOUNDATION_EXPORT const unsigned char ChartSDKVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ChartSDK/PublicHeader.h>
|
koala999cn/kGraph
|
src/core/KtConnected.h
|
<filename>src/core/KtConnected.h
#pragma once
#include "KtBfsIter.h"
// 无向图的连通分量
template<typename GRAPH>
class KtConnected
{
static_assert(!GRAPH::isDigraph(), "KtConnected cannot work for digraph.");
public:
KtConnected(const GRAPH& g)
: count_(0),
cc_(g.order(), -1) {
KtBfsIter<const GRAPH, true> bfs(g, 0);
unsigned id(-1);
for (; !bfs.isEnd(); ++bfs) {
if (bfs.from() == -1)
++id;
cc_[*bfs] = id;
}
count_ = id + 1;
}
// 返回连通分量数量
auto count() const { return count_; }
// 顶点v和顶点w是否连通
bool reachable(unsigned v, unsigned w) const {
return cc_[v] == cc_[w];;
}
// 返回节点v所在连通分量的id, 0 <= id < count().
unsigned operator[](unsigned v) const {
return cc_[v];
}
private:
unsigned count_; // 连通分量的数量
std::vector<unsigned> cc_; // cc_[i]表示顶点i对应的连通分量序号
};
|
koala999cn/kGraph
|
src/util/resort.h
|
<reponame>koala999cn/kGraph
#pragma once
#include <vector>
#include <assert.h>
#include "../core/KtAdjIter.h"
// 对图g的顶点按照order进行重排序,即g[v]变为g[order[v]]
// GRAPH - 图类型
// ORDER - 具[]操作符的类型
template<class GRAPH, class ORDER>
void resort(GRAPH& g, const ORDER& order)
{
using edge_type = typename GRAPH::edge_type;
using vertex_index_t = typename GRAPH::vertex_index_t;
auto E = g.size(); // 用于verify
std::vector<bool> flags(g.order(), false); // 用于标记顶点flags[i]是否已重排序
// 轮询顶点进行重排,主要操作是将顶点v的出边调整为顶点order[v]的出边
for (auto v = 0u; v < g.order(); v++) {
if (flags[v]) continue;
// 收集顶点v的出边
std::vector<std::pair<vertex_index_t, edge_type>> v_outEdges;
auto iter = KtAdjIter(g, v);
for (; !iter.isEnd(); ++iter)
v_outEdges.emplace_back(*iter, iter.edge());
do {
flags[v] = true;
auto nv = order[v]; // 顶点v将重排为nv
// 将顶点v的出边调整为nv的出边之前,先保存nv的出边,以免信息丢失
std::vector<std::pair<vertex_index_t, edge_type>> nv_outEdges;
if (!flags[nv]) { // 若nv已处理,则出边信息已重排过,不必再收集保留
auto iter = KtAdjIter(g, nv);
for (; !iter.isEnd(); ++iter)
nv_outEdges.emplace_back(*iter, iter.edge());
}
// 出边调整:outEdges(v) -> outEdges(nv)
g.eraseOutEdges(nv);
for (const auto& e : v_outEdges)
g.addEdge(nv, order[e.first], e.second);
// 顺着v -> order[v] -> order[order[v]] -> ... 一直往前走
v = nv;
std::swap(v_outEdges, nv_outEdges);
} while (!flags[v]);
}
assert(g.size() == E);
}
|
koala999cn/kGraph
|
src/core/KtMinSpanTree.h
|
<filename>src/core/KtMinSpanTree.h<gh_stars>0
#pragma once
#include <vector>
#include <algorithm>
#include "KtWeightor.h"
#include "KtBfsIter.h"
#include "../base/union_find_set.h"
// 最小生成树:加权图的最小生成树是一颗生成树,其权(所有边的权值之和)不会大于其它任何生成树的权。
template<typename GRAPH, typename WEIGHTOR>
class KtMst
{
static_assert(!GRAPH::isDigraph(), "KtMst cannot instantiated with Digraph.");
public:
using weight_type = typename WEIGHTOR::weight_type;
using vertex_index_t = typename GRAPH::vertex_index_t;
KtMst(const GRAPH& g) : graph_(g), dist_(0.0) {
//assert(g.isConnected());
mst_.reserve(g.order() - 1);
}
// 是否成功生成mst
bool ok() const { return mst_.size() == graph_.order() - 1; }
// 获取mst的第i条边,i < V - 1
auto operator[](unsigned i) const {
return mst_[i];
}
// mst的累加权值
double distance() const {
return dist_;
}
// 生成并返回MST的图表示,图类型为G
template<typename G>
G toGraph() const {
G g(mst_.size() + 1);
for(const auto& e : mst_) {
unsigned v = e.first, w = e.second;
g.addEdge(v, w, graph_.getEdge(v, w));
}
return g;
}
protected:
struct KpEdge_ {
vertex_index_t from, to;
weight_type wt;
};
static std::vector<KpEdge_> edges(const GRAPH& g) {
std::vector<KpEdge_> es; es.reserve(g.size());
KtBfsIter<const GRAPH, true, true> iter(g, 0);
for (; !iter.isEnd(); ++iter)
es.push_back({ iter.from(), *iter, WEIGHTOR{}(iter.edge()) });
assert(es.size() == g.size());
return es;
}
protected:
const GRAPH& graph_;
std::vector<std::pair<unsigned, unsigned>> mst_; // mst的V-1条边
double dist_; // mst的权值累计
};
// Prim是最简单的MST算法,而且对于稠密图也是首选方法。
// 算法的核心思想:维护一个图的剪切,它由树顶点(选择放入MST)和非树顶点(尚未选择放入MST)组成,
// 通过在MST中放置任意一个顶点,以此作为开始,再在MST中放入一条最小交叉边(它将非树顶点调整为树顶点),
// 并重复此操作V-1次,从而将所有顶点都放在树上。
// Prim算法的运行时间与V^2成正比,因此对于稠密图是线性的。
// @WEIGHTOR:从value到weight的转换子
// @minimum:为true则取最小权值,否则取最大权值
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtMstPrim : public KtMst<GRAPH, WEIGHTOR>
{
using super_ = KtMst<GRAPH, WEIGHTOR>;
using typename super_::weight_type;
using super_::mst_;
using super_::dist_;
public:
KtMstPrim(const GRAPH& g) : super_{g} {
WEIGHTOR wtor;
unsigned min = -1;
unsigned V = g.order();
assert(mst_.size() == 0);
std::vector<bool> non_mst(V, true); // 元素i标记顶点i是否不在mst树中
std::vector<unsigned> fr(V, -1); // fr[i]存储与顶点i连接的最小权值边的顶点
std::vector<weight_type> wt(V, WEIGHTOR{}.worst_weight); // wt[i]存储与顶点i连接的边的最小权值
for(unsigned v = 0; min != 0; v = min) { // v表示新加入mst顶点集的顶点
min = 0; // 用来存储此轮搜索中,与mst顶点集相连的最小权值交叉边顶点
for(unsigned w = 1; w < g.order(); w++) {
if(non_mst[w]) { // 遍历不在mst顶点集中的顶点,找到最小交叉边
if(g.hasEdge(v, w)) { // 只需判断新加入mst顶点v与w的权值是否更小
auto e = g.getEdge(v, w);
double p = wtor(e);
if(wtor.comp(p, wt[w]))
wt[w] = p, fr[w] = v;
}
if(wtor.comp(wt[w], wt[min])) min = w; // 发现一条更小的权值边,记录它
}
}
if(min) {
non_mst[min] = false;
mst_.push_back({fr[min], min});
dist_ = wtor.acc(dist_, wt[min]);
}
}
}
};
// Kruskal遍历边来生成MST:
// 1. 首先将V个顶点看作V颗单顶点树;
// 2. 选择权值最小的边,合并两颗树;
// 3. 若构成环,则舍弃改条边;
// 4. 重复2,直至找到组成MST的V-1条边
// 算法时间复杂度E*lgE,其中排序开销占主导地位
template<typename GRAPH, typename WEIGHTOR = default_wtor<GRAPH>>
class KtMstKruskal : public KtMst<GRAPH, WEIGHTOR>
{
using super_ = KtMst<GRAPH, WEIGHTOR>;
using super_::mst_;
using super_::dist_;
public:
KtMstKruskal(const GRAPH& g) : super_{g} {
auto all_edges = super_::edges(g);
// 降序排序,权值最小的边在尾部,方便出栈
std::sort(std::begin(all_edges), std::end(all_edges),
[](const auto& x1, const auto& x2) { return WEIGHTOR{}.comp(x2.wt, x1.wt); });
const unsigned V = g.order();
const unsigned E = g.size();
union_find_set uf(V);
assert(super_::mst_.size() == 0);
for(unsigned i = 0; i < E && mst_.size() < V - 1; i++) {
const auto& e = all_edges.back();
unsigned v = e.from, w = e.to;
if(uf.unite(v, w)) { // 若合并成功,则一定无环
mst_.push_back({ e.from, e.to });
dist_ = WEIGHTOR{}.acc(dist_, e.wt);
}
all_edges.pop_back();
}
}
};
// Boruvka与Kruskal算法类似,都是从森林开始构建mst。
// 不同点在于Kruskal每次增加1条最小跨边,而Boruvka每次增加1批。
// 算法时间复杂度E*lgV
template<typename GRAPH, typename WEIGHTOR = default_wtor<GRAPH>>
class KtMstBoruvka : public KtMst<GRAPH, WEIGHTOR>
{
using weight_type = typename WEIGHTOR::weight_type;
using super_ = KtMst<GRAPH, WEIGHTOR>;
using super_::mst_;
using super_::dist_;
public:
KtMstBoruvka(const GRAPH& g) : super_{g} {
assert(mst_.size() == 0);
const unsigned V = g.order();
auto edges = super_::edges(g);
unsigned N; // 有效边数量
std::vector<const typename super_::KpEdge_*> b;
union_find_set uf(V);
// 从单顶点子树开始
for(unsigned E = unsigned(edges.size()); E != 0 && mst_.size() < V - 1; E = N) {
b.assign(V, nullptr);
N = 0;
// 搜索连接每两颗子树的最小跨边,存储到数组b中。
for(unsigned h = 0; h < E; h++) {
const auto& e = edges[h];
unsigned i = uf.find(e.from), j = uf.find(e.to);
if(i == j) continue;
edges[N] = e; // 复制有效边,等同于删除无效边
if (b[i] == nullptr || WEIGHTOR{}.comp(e.wt, b[i]->wt)) b[i] = &edges[N];
if (b[j] == nullptr || WEIGHTOR{}.comp(e.wt, b[j]->wt)) b[j] = &edges[N];
++N;
}
// 将存储在b中的最小跨边,按照查并集的模式添加到mst。
for(unsigned h = 0; h < V; h++)
if(b[h] != nullptr && uf.unite(b[h]->from, b[h]->to)) {
mst_.push_back(std::pair<unsigned, unsigned>(b[h]->from, b[h]->to));
dist_ = WEIGHTOR{}.acc(dist_, b[h]->wt);
}
}
}
};
#include "KtPfsIter.h"
template<typename GRAPH, typename WEIGHTOR = default_wtor<GRAPH>>
class KtMstPfs : public KtMst<GRAPH, WEIGHTOR>
{
using edge_type = typename GRAPH::edge_type;
using weight_type = typename WEIGHTOR::weight_type;
using super_ = KtMst<GRAPH, WEIGHTOR>;
using super_::mst_;
using super_::dist_;
public:
KtMstPfs(const GRAPH& g) : super_{ g } {
assert(super_::mst_.size() == 0);
struct Prior {
auto operator()(unsigned, unsigned, const edge_type& val) {
return WEIGHTOR{}(val);
}
};
struct Comp {
auto operator()(const weight_type& a, const weight_type& b) {
return WEIGHTOR{}.comp(a, b);
}
};
KtPfsIter<const GRAPH, Prior, Comp> iter(g, 0);
++iter; // skip v0
for (; !iter.isEnd() ; ++iter) {
if (!iter.isPopped(*iter)) {
mst_.push_back(iter.edge());
dist_ = WEIGHTOR{}.acc(dist_, iter.prior());
if (mst_.size() == g.order() - 1)
break;
}
}
}
};
|
koala999cn/kGraph
|
src/core/KtAdjGraphSparseImpl.h
|
<reponame>koala999cn/kGraph
#pragma once
#include "KtAdjGraphBase.h"
#include "edge_traits.h"
#include "graph_traits.h"
#include <assert.h>
// 基于稀疏阵的邻接矩阵图实现
namespace kPrivate
{
// 基于vector的稀疏矩阵
template<typename EDGE_TYPE>
using underly_edge_t = edge_has_to_t<EDGE_TYPE>;
template<typename EDGE_TYPE>
using row_type = std::vector<underly_edge_t<EDGE_TYPE>>;
template<typename EDGE_TYPE>
class KtSpMatrix : public std::vector<row_type<EDGE_TYPE>>
{
public:
using super_ = std::vector<row_type<EDGE_TYPE>>;
auto rows() const { return super_::size(); }
decltype(auto) row(unsigned v) {
return KtRange(super_::at(v).begin(),
static_cast<unsigned>(super_::at(v).size()));
}
decltype(auto) row(unsigned v) const {
return KtRange(super_::at(v).cbegin(),
static_cast<unsigned>(super_::at(v).size()));
}
};
}
template<typename EDGE_TYPE, typename VERTEX_TYPE = void>
class KtAdjGraphSparseImpl : public KtAdjGraphBase<kPrivate::KtSpMatrix<EDGE_TYPE>, VERTEX_TYPE>
{
public:
using super_ = KtAdjGraphBase<kPrivate::KtSpMatrix<EDGE_TYPE>, VERTEX_TYPE>;
using edge_type = EDGE_TYPE;
using vertex_type = VERTEX_TYPE;
using edge_iter = typename graph_traits<super_>::edge_iter;
using const_edge_iter = typename graph_traits<super_>::const_edge_iter;
using underly_edge_t = typename graph_traits<super_>::underly_edge_t;
constexpr static const edge_type& null_edge = edge_traits<edge_type>::null_edge;
static_assert(std::is_same_v<kPrivate::underly_edge_t<EDGE_TYPE>, underly_edge_t>, "edge type mismatch");
static_assert(edge_traits_helper<edge_traits<underly_edge_t>>::has_to, "edge type construct error");
using super_::E_;
using super_::adjMat_;
using super_::order;
using super_::outedges;
KtAdjGraphSparseImpl() = default;
// 重置图为nv顶点.
void reset(unsigned nv) {
E_ = 0;
adjMat_.clear(); adjMat_.resize(nv);
if constexpr (!std::is_void_v<vertex_type>)
super_::vertexes_.resize(nv);
}
// 预留nv个顶点和ne条边的存储.
void reserve(unsigned nv, unsigned ne) {
adjMat_.reserve(nv);
if constexpr (!std::is_void_v<vertex_type>)
super_::vertexes_.reserve(nv);
}
// 对顶点v预留ne条边的存储.
void reserveEdges(unsigned v, unsigned ne) {
adjMat_[v].reserve(ne);
}
template<typename T = vertex_type, std::enable_if_t<std::is_void_v<T>, bool> = true>
unsigned addVertex() {
adjMat_.push_back(kPrivate::row_type<edge_type>());
return static_cast<unsigned>(adjMat_.rows()) - 1;
}
template<typename T, std::enable_if_t<!std::is_void_v<T>
&& std::is_convertible_v<T, vertex_type>, bool> = false>
unsigned addVertex(const T& v) {
adjMat_.push_back(kPrivate::row_type<edge_type>());
super_::vertexes_.push_back(vertex_type(v));
return super_::vertexes_.size();
}
template<typename T, std::enable_if_t<!std::is_void_v<T>
&& std::is_same_v<T, vertex_type>, bool> = false>
unsigned addVertex(T&& v) {
adjMat_.push_back(kPrivate::row_type<edge_type>());
super_::vertexes_.push_back(std::move(v));
return super_::vertexes_.size();
}
template<bool dummy = false>
edge_iter addEdge(unsigned from, edge_iter pos, const edge_type& edge) {
assert(from < order());
if constexpr (!dummy) ++E_;
return adjMat_[from].insert(pos, edge);
}
// 删除顶点v
// 调用该函数前,确保已删除v相接的所有边
void eraseVertex(unsigned v) {
assert(v < order() && adjMat_[v].empty());
adjMat_.erase(std::next(adjMat_.begin(), v));
if constexpr (!std::is_void_v<vertex_type>)
super_::vertexes_.erase(std::next(super_::vertexes_.begin(), v));
}
// 删除顶点v的出边e
template<bool dummy = false>
edge_iter eraseEdge(unsigned v, edge_iter e) {
assert(e >= outedges(v).begin() && e < outedges(v).end());
if constexpr (!dummy) --E_;
return adjMat_[v].erase(e);
}
// const_edge_iter版本
template<bool dummy = false>
edge_iter eraseEdge(unsigned v, const_edge_iter e) {
assert(e >= outedges(v).cbegin() && e < outedges(v).cend());
if constexpr (!dummy) --E_;
return adjMat_[v].erase(e);
}
// 删除first到last之间的边
template<bool dummy = false>
edge_iter eraseEdges(unsigned v, edge_iter first, edge_iter last) {
assert(first >= outedges(v).begin() && last <= outedges(v).end());
if constexpr (!dummy)
E_ -= static_cast<decltype(E_)>(std::distance(first, last));
return adjMat_[v].erase(first, last);
}
};
template<typename EDGE_TYPE, typename VERTEX_TYPE>
struct graph_traits<KtAdjGraphSparseImpl<EDGE_TYPE, VERTEX_TYPE>>
: public graph_traits<KtAdjGraphBase<kPrivate::KtSpMatrix<EDGE_TYPE>, VERTEX_TYPE>>
{
constexpr static bool reshapable = true;
constexpr static bool immutable = false;
};
|
koala999cn/kGraph
|
src/core/KtDfsIterX.h
|
<reponame>koala999cn/kGraph
#pragma once
#include "KtDfsIter.h"
// KtDfsIter的加强版,总是stopAtPopping,主要新增2项新功能支持:
// 一是新增顶点的最小前序编号支持(low值),表示该顶点为根的子树中任何回边所引用的最小前序编号(order值)
// 二是新增判断当前顶点与其父顶点是否为桥的支持
// low值定义: low(v) = min(pushOrder[v], low[w], pushOrder[k])
// 式中:w是顶点v的孩子节点,k是顶点v的回边祖先节点
template<typename GRAPH, bool fullGraph = false>
class KtDfsIterX : public KtDfsIter<GRAPH, false, true, true>
{
using super_ = KtDfsIter<GRAPH, false, true, true>;
public:
KtDfsIterX(GRAPH& graph, unsigned v = 0) : super_(graph, v), low_(graph.order(), -1) {
low_[v] = pushingIndex();
}
using super_::pushingIndex;
using super_::pushIndex;
using super_::from;
using super_::isEnd;
using super_::isPushing;
using super_::isPopping;
using super_::isBack;
using super_::firstUnvisited;
// 重写父类的++操作符重载
void operator++() {
super_::operator++();
if(!isEnd()) {
unsigned w = **this;
if(isPushing()) {
assert(pushIndex(w) == -1);
low_[w] = pushingIndex(); // 初始化low(v) = pushOrder[v]
}
else {
unsigned v = from();
if (v != -1) {
if (isBack()) {
if (low_[v] > pushIndex(w))
low_[v] = pushIndex(w); // low(v) = min(low[v], pushOrder[k])
}
else if (low_[v] > low_[w])
low_[v] = low_[w]; // low(v) = min(low[v], low[w])
}
}
}
else if (fullGraph) {
unsigned unvisted = firstUnvisited();
if (unvisted != -1)
start(unvisted);
}
}
// 重写父类的start方法,以同步更新low值
void start(unsigned v) {
super_::start(v);
low_[v] = pushingIndex();
}
unsigned lowIndex(unsigned v) const {
return low_[v];
}
void resetLowIndex(unsigned v) {
low_[v] = -1;
}
bool isBridge() const {
unsigned v = **this;
return /*from() != -1 && */isPopping() && lowIndex(v) == pushIndex(v);
}
private:
std::vector<unsigned> low_; // 存储各节点展开子孙节点所连接节点的最小序号
};
|
koala999cn/kGraph
|
src/util/loop.h
|
#pragma once
#include "../core/KtDfsIter.h"
template<typename GRAPH>
bool has_self_loop(const GRAPH& g)
{
auto V = g.order();
for(decltype(V) i = 0; i < V; i++)
if(g.hasEdge(i, i))
return true;
return false;
}
// 删除自环
template<typename GRAPH>
void erase_self_loop(GRAPH& g)
{
auto V = g.order();
for(decltype(V) i = 0; i < V; i++)
if(g.hasEdge(i, i))
g.eraseEdge(i, i);
}
// 一个有向图是DAG,当且仅当在使用DFS检查每条边时未遇到任何回边
template<typename GRAPH>
bool has_loop(const GRAPH& g)
{
KtDfsIter<const GRAPH, true, true, true> iter(g, 0);
while(!iter.isEnd()) {
if(iter.isBack())
return true;
++iter;
}
return false;
}
// 删除环
template<typename GRAPH>
void erase_loop(GRAPH& g)
{
// 删除回边. 自环也是回边
KtDfsIter<GRAPH, true, true> iter(g, 0);
while(!iter.isEnd()) {
if(iter.isBack())
iter.erase();
else
++iter;
}
}
|
koala999cn/kGraph
|
src/core/KtTransitiveClosure.h
|
<gh_stars>0
#pragma once
#include <type_traits>
#include <assert.h>
#include "../GraphX.h"
#include "KtDfsIter.h"
#include "KtStronglyConnected.h"
// 计算图的闭包的基类
// @useSpare: 是否使用稀疏图保存闭包结果
// TODO: 闭包结果不包含路径信息和权值信息
template<typename GRAPH, bool useSpare>
class KtTcAbstract
{
public:
using vertex_index_t = typename GRAPH::vertex_index_t;
using closure_graph_t = std::conditional_t<useSpare, DigraphSx<bool>, DigraphDx<bool>>;
explicit KtTcAbstract(const GRAPH& g) : clsg_(g.order()){}
KtTcAbstract(const KtTcAbstract& c) : clsg_(c.clsg) {}
KtTcAbstract(KtTcAbstract&& c) : clsg_(std::move(c.clsg_)) {}
KtTcAbstract& operator =(const KtTcAbstract& rhs) {
clsg_ = rhs.clsg_;
return *this;
}
KtTcAbstract& operator =(KtTcAbstract&& rhs) {
clsg_ = std::move(rhs.clsg_);
return *this;
}
// 判断闭包图中v是否可达w
bool reachable(vertex_index_t v, vertex_index_t w) const {
return clsg_.hasEdge(v, w);
}
auto operator->() const { return &clsg_; }
protected:
void set_(vertex_index_t v, vertex_index_t w) {
if (reachable(v, w))
clsg_.addEdge(v, w);
}
auto adjIter_(unsigned v) const {
return KtAdjIter(clsg_, v);
}
private:
closure_graph_t clsg_; // 闭包图
};
/*
基于Warshall算法的闭包实现.
Warshall算法将基于布尔矩阵的传递闭包实现时间复杂度从V ^ 3 * log2V降低为V ^ 3
*/
template<typename GRAPH, bool useSpare = false>
class KtTcWarshall : public KtTcAbstract<GRAPH, useSpare>
{
public:
using super_ = KtTcAbstract<GRAPH, useSpare>;
using super_::reachable;
using super_::set_;
KtTcWarshall(const GRAPH& g) : super_(g) {
auto V = g.order();
for (unsigned v = 0; v < V; v++)
for (unsigned w = 0; w < V; w++)
if (v == w || g.hasEdge(v, w)) // 用谓词初始化,并确保自环
set_(v, w);
// Warshall算法
for (unsigned i = 0; i < V; i++)
for (unsigned s = 0; s < V; s++)
if (reachable(s, i)) {
auto iter = super_::adjIter_(i);
for (; !iter.isEnd(); ++iter)
set_(s, *iter);
}
}
};
/*
基于DFS的闭包实现.
它以G的各个顶点作为开始完成一个单独的DFS,计算其可达的顶点集,以此计算传递闭包。
*/
template<typename GRAPH, bool useSpare = false>
class KtTcDfs : public KtTcAbstract<GRAPH, useSpare>
{
public:
using super_ = KtTcAbstract<GRAPH, useSpare>;
using super_::reachable;
using super_::set_;
KtTcDfs(const GRAPH& g) : super_(g) {
unsigned V = g.order();
for (unsigned i = 0; i < V; i++)
set_(i, i);
for (unsigned v = 0; v < V; v++) {
KtDfsIter<const GRAPH> iter(g, v);
assert(iter.from() == -1);
++iter; // skip edge(-1, v)
for (; !iter.isEnd(); ++iter)
if (iter.isTree())
set_(v, *iter);
}
}
};
/*
DAG的传递闭包,基于DFS算法实现。
相比KtClosureDfs,主要利用DAG的特性进行优化.
1.没有回边
2.下边可以忽略,即不用递归展开,也不用回溯传递闭包
3.跨边不用递归展开,直接回溯即可
*/
template<typename GRAPH, bool useSpare = false>
class KtTcDag : public KtTcAbstract<GRAPH, useSpare>
{
public:
using super_ = KtTcAbstract<GRAPH, useSpare>;
using super_::reachable;
using super_::set_;
KtTcDag(const GRAPH& g) : super_(g) {
//assert(g.isDag());
unsigned V = g.order();
for (unsigned i = 0; i < V; i++)
set_(i, i);
KtDfsIter<const GRAPH, true, true, true> iter(g, 0);
for (; !iter.isEnd(); ++iter) {
unsigned p = iter.from();
if (p == -1)
continue; // skip edge(-1, v)
unsigned v = *iter;
if (!iter.isPopping())
set_(p, v);
assert(!iter.isBack()); // DAG没有回边
if (iter.isCross() || iter.isPopping()) {
auto iter = super_::adjIter_(v);
for (; !iter.isEnd(); ++iter)
set_(p, *iter);
}
}
}
};
/*
基于强分量的传递闭包实现.
*/
template<typename GRAPH, bool useSpare = false>
class KtTcScc
{
public:
using vertex_index_t = typename GRAPH::vertex_index_t;
KtTcScc(const GRAPH& g) : scc_(g) {
// 以每个强连通分量为一个顶点构建DAG
DigraphDx<bool> K(scc_.count());
for (unsigned v = 0; v < g.order(); v++) {
auto iter = KtAdjIter(g, v);
while (!iter.isEnd()) {
auto x = scc_[v];
auto y = scc_[*iter];
if (x != y && !K.hasEdge(x, y)) // 消除自环
K.addEdge(x, y);
++iter;
}
}
// 使用基于DAG的传递闭包优化算法
dagCls_ = new KtTcDag<DigraphDx<bool>>(K);
}
~KtTcScc() { delete dagCls_; }
bool reachable(vertex_index_t v, vertex_index_t w) const {
return dagCls_->reachable(scc_[v], scc_[w]);
}
private:
KtStronglyConnectedTar<GRAPH> scc_;
KtTcDag<DigraphDx<bool>, useSpare>* dagCls_;
};
|
koala999cn/kGraph
|
src/util/reachable.h
|
<reponame>koala999cn/kGraph
#pragma once
#include "../core/KtBfsIter.h"
// 顶点v是否可达w,即是否存在一条从v到w的路径
template<typename GRAPH>
bool is_reachable(const GRAPH& g, unsigned v, unsigned w)
{
KtBfsIter<const GRAPH> iter(g, v);
for (; !iter.isEnd(); ++iter)
if (*iter == w)
return true;
return false;
}
// 设置v可达的顶点标记
template<typename GRAPH>
std::vector<bool> get_reachable(const GRAPH& g, unsigned v)
{
std::vector<bool> flags(g.order(), false);
KtBfsIter<const GRAPH> iter(g, v);
for (; !iter.isEnd(); ++iter)
flags[*iter] = true;
return flags;
}
// 移除v不可达的顶点
template<typename GRAPH>
void erase_unreachable(GRAPH& g, unsigned v)
{
auto flags = get_reachable(v);
// 逆序删除v不可达的顶点
for (unsigned i = unsigned(flags.size()) - 1; i != -1; i--)
if (!flags[i])
g.eraseVertex(i);
}
|
koala999cn/kGraph
|
src/core/KtPfsIter.h
|
#pragma once
#include <queue>
#include <assert.h>
#include "KtAdjIter.h"
// 基于优先队列的图遍历
// PRIORITOR - 计算优先度的函数子,输入参数为:from, to, value
// COMP - 比较优先度的函数子
template <typename GRAPH, typename PRIORITOR, typename COMP, bool fullGraph = false>
class KtPfsIter
{
public:
using edge_type = typename GRAPH::edge_type;
using prior_type = decltype(std::declval<PRIORITOR>()(0, 0, edge_type(0))); // 得到PRIORITOR算子的返回类型
using element_type = std::pair<std::pair<unsigned, unsigned>, prior_type>;
struct Comp {
bool operator()(const element_type& a, const element_type& b) {
return COMP{}(b.second, a.second);
}
};
using pfs_queue = std::priority_queue<element_type, std::vector<element_type>, Comp>;
public:
KtPfsIter(GRAPH& g, unsigned v0)
: graph_(g)
, v0_(v0)
, isPushed_(g.order(), false)
, st_(g.order(), -1) {
start(v0);
}
void operator++() {
assert(!isEnd());
auto x = pq_.top().first; pq_.pop();
unsigned w = x.second;
st_[w] = x.first;
auto iter= KtAdjIter(graph_, w);
for (; !iter.isEnd(); ++iter) {
unsigned t = *iter;
if (!isPushed(t)) {
pq_.emplace(std::pair<unsigned, unsigned>{w, t}, PRIORITOR{}(w, t, iter.edge())); // put it
isPushed_[t] = true;
}
else if(!isPopped(t) // isPopped(v0)始终为false
&& (graph_.isDigraph() || t != x.first && t != v0_) // 忽略无向图的回边
)
pq_.emplace(std::pair<unsigned, unsigned>{w, t}, PRIORITOR{}(w, t, iter.edge())); // update it
}
if (fullGraph && isEnd()) {
auto pos = std::find(isPushed_.begin(), isPushed_.end(), false);
if (pos != isPushed_.end())
start(unsigned(std::distance(isPushed_.begin(), pos)));
}
}
// 返回当前正在游历的顶点
unsigned operator*() const {
assert(!isEnd());
return pq_.top().first.second;
}
// 与当前顶点(to顶点)构成边的from顶点
unsigned from() const {
assert(!isEnd());
return pq_.top().first.first;
}
auto edge() const {
assert(!isEnd());
return pq_.top().first;
}
auto prior() const {
assert(!isEnd());
return pq_.top().second;
}
unsigned from(unsigned w) const {
return st_[w];
}
bool isEnd() const { return pq_.empty(); }
// 从顶点v开始接续进行广度优先遍历
void start(unsigned v) {
assert(isEnd() && !isPushed(v));
pq_.emplace(std::pair<unsigned, unsigned>{-1, v}, 0);
isPushed_[v] = true;
}
bool isPushed(unsigned v) const { return isPushed_[v]; }
bool isPopped(unsigned v) const { return st_[v] != -1; }
private:
GRAPH& graph_;
unsigned v0_;
std::vector<bool> isPushed_;
pfs_queue pq_; // 边缘带
std::vector<unsigned> st_; // 树
};
|
koala999cn/kGraph
|
src/util/is_connected.h
|
#pragma once
#include "../core/KtBfsIter.h"
// 判断是否连通图
template<typename GRAPH>
bool is_connected(const GRAPH& g)
{
KtBfsIter<const GRAPH> iter(g, 0);
decltype(g.order()) V(0);
for (; !iter.isEnd(); ++iter)
++V;
return V == g.order();
}
|
koala999cn/kGraph
|
src/core/KtDfsIter.h
|
<reponame>koala999cn/kGraph<gh_stars>0
#pragma once
#include <vector>
#include <assert.h>
// 统一有向图与无向图的深度优先遍历模板框架,通过模板参数可支持多种遍历范式。
// 模板参数:
// -- stopAtPopping,若为true,则每个顶点出栈时迭代器暂停,用户有机会处理出栈顶点.
// -- fullGraph,参见KtBfsIter.
// -- modeEdge,参见KtBfsIter.
// 当modeEdge为true, stopAtPopping为false时,则实质为边迭代器,起始顶点被跳过,已保证起始状态即为第一条边
// 当modeEdge为true, stopAtPopping为true时,初始状态仍返回起始顶点,此时from()返回-1.
template<typename GRAPH, bool fullGraph = false, bool modeEdge = false, bool stopAtPopping = false>
class KtDfsIter
{
public:
using graph_type = GRAPH;
using vertex_index_t = typename graph_type::vertex_index_t;
using edge_type = typename GRAPH::edge_type;
using adj_vertex_iter = KtAdjIter<graph_type>;
using const_edge_ref = decltype(std::declval<adj_vertex_iter>().edge());
constexpr static vertex_index_t null_vertex = -1;
// graph -- 待遍历的图
// startVertex -- 遍历的起始顶点,-1表示只构建迭代器,需要另外调用start方法开始遍历
KtDfsIter(GRAPH& graph, vertex_index_t startVertex)
: graph_(graph),
v_(null_vertex),
pushOrd_(graph.order(), null_vertex),
popOrd_(graph.order(), null_vertex),
pushIdx_(0), popIdx_(0) {
if (startVertex != null_vertex)
start(startVertex);
}
void operator++() {
assert(!isEnd());
if (isPopping()) { // 处理出栈顶点
assert(popOrd_[v_] == null_vertex);
popOrd_[v_] = popIdx_++;
todo_.pop_back();
}
else {
if (todo_.size() > 1)
++todo_.back();
if (isPushing()) {
pushOrd_[v_] = pushIdx_++;
todo_.push_back(adj_vertex_iter(graph_, v_));
}
}
advancePost_();
}
// 返回当前正在游历的顶点
vertex_index_t operator*() const { return v_; }
// 与当前顶点(to顶点)构成边的from顶点
vertex_index_t from() const {
assert(!isEnd());
return isPopping() ? grandpa() :
todo_.size() > 1 ? todo_.back().from() : null_vertex;
}
// 返回边(from, to)的值
const_edge_ref edge() const {
assert(!isEnd() && from() != null_vertex);
return todo_.back().edge();
}
bool isEnd() const { return v_ == null_vertex; }
// 从顶点v开始接续进行广度优先遍历
void start(vertex_index_t v) {
assert(isEnd() && pushOrd_[v] == null_vertex);
todo_.clear();
todo_.push_back(adj_vertex_iter(graph_));
v_ = v;
if (modeEdge && !stopAtPopping)
++(*this); // skip v0
}
void erase() {
assert(!isEnd() && from() != null_vertex);
if (isPopping()) { // 处理出栈顶点
assert(popOrd_[v_] == null_vertex);
popOrd_[v_] = popIdx_++;
todo_.pop_back();
}
todo_.back().erase();
advancePost_();
}
/*
BGL中关于树边、回边、下边、跨边的定义:
- Tree edges are edges in the search tree(or forest) constructed by running a graph search algorithm over a graph.
An edge(u, v) is a tree edge if v was first discovered while exploring edge(u, v).
- Back edges connect vertices to their ancestors in a search tree.
So for edge(u, v) the vertex v must be the ancestor of vertex u.
Self loops are considered to be back edges.
- Forward edges are non-tree edges(u, v) that connect a vertex u to a descendant v in a search tree.
- Cross edges are edges that do not fall into the above three categories.
*/
// 树边,表示递归调用(即第一次访问该节点)
bool isTree() const {
return pushOrd_[v_] == -1;
}
// 回边,表示当前节点是前序节点的祖先
bool isBack() const {
return !isTree() && !isPopping() && popOrd_[v_] == -1;
}
// 下边/前边,表示当前节点是前序节点的子孙
bool isDown() const {
//return !isTree() && !isBack() && pushOrd_[**this] > pushOrd_[from()];
assert(pushOrd_[from()] != -1);
return static_cast<int>(pushOrd_[v_]) > static_cast<int>(pushOrd_[from()]);
}
// 跨边,表示当前节点既不是前序节点的祖先,也不是子孙
bool isCross() const {
//return !isTree() && !isBack() && !isDown();
return GRAPH::isDigraph() && popOrd_[v_] != -1; // 只有有向图才有跨边
}
// 当前节点是否正在入栈,对应于递归的入口
bool isPushing() const { return isTree(); }
// 当前节点是否正在出栈,对应于递归的出口
bool isPopping() const { return stopAtPopping && !isPushing() && todo_.back().isEnd(); }
// 获取顶点v的入栈/出栈次序,用于事后检测
unsigned pushIndex(vertex_index_t v) const { return pushOrd_[v]; }
unsigned popIndex(vertex_index_t v) const { return popOrd_[v]; }
// 获取当前的入栈/出栈序号
unsigned pushingIndex() const { return pushIdx_; }
unsigned poppingIndex() const { return popIdx_; }
vertex_index_t firstUnvisited() const {
auto pos = std::find(pushOrd_.begin(), pushOrd_.end(), null_vertex);
return pos == pushOrd_.end() ? -1
: static_cast<vertex_index_t>(std::distance(pushOrd_.begin(), pos));
}
graph_type& graph() { return graph_; }
private:
// 返回当前顶点的祖父顶点,即from之from
vertex_index_t grandpa() const {
return todo_.size() > 2 ? todo_[todo_.size() - 2].from() : null_vertex;
}
// 步进或删除的后处理
void advancePost_() {
// 检测当前顶点是否需要跳过
while (todo_.size() > 1) {
auto& iter = todo_.back();
// 移除已结束的迭代器
if (iter.isEnd()) {
if (!stopAtPopping) {
popOrd_[iter.from()] = popIdx_++;
todo_.pop_back();
continue;
}
break; // stop at popping
}
assert(!isPopping() && !iter.isEnd());
// 防止无向图的顶点回溯
if (!GRAPH::isDigraph() && *iter == grandpa()) {
++iter;
continue;
}
// 跳过已遍历的顶点或边
bool needSkip = false;
if (modeEdge) {
if (!GRAPH::isDigraph() && popOrd_[*iter] != -1) // 对于无向图,若某顶点已出栈,则与之邻接的边必然已遍历
needSkip = true;
}
else if (pushOrd_[*iter] != -1) // 跳过已遍历的顶点,确保每个顶点只遍历一次
needSkip = true;
if (needSkip) {
++iter;
continue;
}
break;
}
// 更新v_和接续遍历
if (todo_.size() <= 1) {
v_ = null_vertex; // 设置终止标记
if (fullGraph) {
unsigned unvisted = firstUnvisited();
if (unvisted != null_vertex)
start(unvisted); // 接续遍历
}
}
else {
auto& iter = todo_.back();
v_ = iter.isEnd() ? iter.from() : *iter;
}
}
private:
graph_type& graph_;
// 待处理的邻接顶点迭代器
std::vector<adj_vertex_iter> todo_;
vertex_index_t v_; // 正在遍历的顶点
std::vector<unsigned> pushOrd_, popOrd_; // 用于记录各顶点的压栈/出栈顺序
unsigned pushIdx_, popIdx_; // 当前压栈/出栈序号
};
|
koala999cn/kGraph
|
src/base/KtMatrix.h
|
#pragma once
#include <vector>
#include <assert.h>
#include "KtRange.h"
// 一个简单的矩阵模板实现
template<typename T>
class KtMatrix
{
public:
using container = std::vector<T>;
using value_type = typename container::value_type;
using reference = typename container::reference;
using const_reference = typename container::const_reference;
using row_element_iter = typename container::iterator;
using const_row_element_iter = typename container::const_iterator;
using row_range = KtRange<row_element_iter>;
using const_row_range = KtRange<const_row_element_iter>;
KtMatrix() = default;
KtMatrix(const KtMatrix&) = default;
KtMatrix(KtMatrix&& m) = default;
~KtMatrix() = default;
KtMatrix& operator=(const KtMatrix&) = default;
KtMatrix& operator=(KtMatrix&& m) = default;
KtMatrix(unsigned rows, unsigned cols, const_reference initValue) :
rows_(rows), cols_(cols) {
data_.assign(rows * cols, initValue);
}
void resize(unsigned rows, unsigned cols, const_reference init_val) {
rows_ = rows, cols_ = cols;
data_.assign(rows * cols, init_val);
}
void reserve(unsigned rows, unsigned cols) { data_.reserve(rows * cols); }
unsigned rows() const { return rows_; } // 行数
unsigned cols() const { return cols_; } // 列数
void insert(unsigned row, unsigned col, const_reference val) {
data_[row * cols_ + col] = val;
}
// 返回第idx行的迭代范围
auto row(unsigned idx) {
row_element_iter start = std::next(data_.begin(), idx * cols_);
return KtRange<row_element_iter>(start, cols_);
}
auto row(unsigned idx) const {
const_row_element_iter start = std::next(data_.cbegin(), idx * cols_);
return KtRange<const_row_element_iter>(start, cols_);
}
void eraseRow(unsigned idx) {
auto range = row(idx);
data_.erase(range.begin(), range.end());
--rows_;
}
void eraseCol(unsigned idx) {
--cols_;
auto iter = std::next(data_.begin(), idx);
for (unsigned r = 0; r < rows_; r++) {
iter = data_.erase(iter);
if(r != rows_-1)
std::advance(iter, cols_);
}
}
// @val: 新增行的初始值
void appendRow(const_reference val) {
data_.resize(data_.size() + cols_, val);
++rows_;
}
// @val: 新增列的初始值
void appendCol(const_reference val) {
data_.resize(data_.size() + rows_);
auto src = data_.data() + (rows_ - 1) * cols_;
auto dst = data_.end() - 1;
for (unsigned r = 1; r < rows_; r++) { // 首行不移动,所以r从1起
std::copy_backward(src, src + cols_, dst);
*dst = val; // 新增列赋值
src -= cols_;
dst -= cols_ + 1;
}
*(src + cols_) = val; // 首行的新增列赋值
++cols_;
}
private:
unsigned rows_, cols_;
container data_;
};
|
koala999cn/kGraph
|
src/core/KtBfsIter.h
|
<reponame>koala999cn/kGraph<filename>src/core/KtBfsIter.h
#pragma once
#include <queue>
#include <assert.h>
#include "KtAdjIter.h"
// 广度优先遍历
// 模板参数:
// -- fullGraph,若为true,则进行全图迭代,否则仅迭代与v相联通的节点或边。
// -- modeEdge,若为true,则对边进行广度优先遍历,这时顶点可能会多次重复,但每条边只会遍历一次。
// 若为false,则对顶点进行广度优先遍历,这时不能保证每条边都会遍历到或只遍历一次。
// 非modeEdge模式下的初始状态,operator*()返回startVertex,from()方法返回-1
// modeEdge模式下的初始状态,operator*()返回startVertex的第一个邻接顶点,from()方法返回startVertex
template <typename GRAPH, bool fullGraph = false, bool modeEdge = false>
class KtBfsIter
{
public:
using graph_type = GRAPH;
using edge_type = typename GRAPH::edge_type;
using vertex_index_t = typename graph_type::vertex_index_t;
using adj_vertex_iter = KtAdjIter<graph_type>;
using const_edge_ref = decltype(std::declval<adj_vertex_iter>().edge());
constexpr static vertex_index_t null_vertex = -1;
// graph -- 待遍历的图
// startVertex -- 遍历的起始顶点,-1表示只构建迭代器,需要另外调用start方法开始遍历
KtBfsIter(graph_type& graph, vertex_index_t startVertex)
: graph_(graph),
v0_(null_vertex),
isPushed_(graph.order(), false),
isPopped_(graph.order(), false) {
if (startVertex != null_vertex)
start(startVertex);
}
void operator++() {
assert(!isEnd());
if (!isPushed_[v0_]) {
assert(todo_.empty());
isPushed_[v0_] = true;
todo_.push(adj_vertex_iter(graph_, v0_));
} else {
assert(!todo_.empty());
auto& iter = todo_.front();
vertex_index_t v = *iter;
if (!isPushed_[v]) {
isPushed_[v] = true;
todo_.push(adj_vertex_iter(graph_, v));
}
++iter;
}
while (!todo_.empty()) {
auto& iter = todo_.front();
// 移出已到末尾的迭代器
if (iter.isEnd()) {
isPopped_[from()] = true;
todo_.pop();
continue;
}
// 跳过已遍历的顶点或边
if (modeEdge) {
if (!graph_type::isDigraph() && isPopped_[*iter]) { // 对于无向图,若某顶点已出栈,则与之邻接的边必然已遍历
++iter;
continue;
}
}
else {
if (isPushed_[*iter]) { // 跳过已遍历的顶点,确保每个顶点只遍历一次
++iter;
continue;
}
}
break;
}
if (todo_.empty()) {
isPopped_[v0_] = true;
v0_ = null_vertex; // 设置终止标记
}
if (fullGraph && isEnd()) {
auto pos = std::find(isPushed_.begin(), isPushed_.end(), false);
if (pos != isPushed_.end())
start(static_cast<vertex_index_t>(std::distance(isPushed_.begin(), pos)));
}
}
// 返回当前正在游历的顶点
vertex_index_t operator*() const {
return todo_.empty() ? v0_ : *(todo_.front());
}
// 与当前顶点(to顶点)构成边的from顶点
vertex_index_t from() const {
assert(!isEnd());
return todo_.empty() ? null_vertex : todo_.front().from();
}
const_edge_ref edge() const { return todo_.front().edge(); }
bool isEnd() const { return v0_ == null_vertex; }
// 从顶点v开始接续进行广度优先遍历
void start(vertex_index_t v) {
assert(isEnd() && !isPushed_[v]);
v0_ = v;
if (modeEdge) ++(*this); // skip v0
}
bool isPushed(vertex_index_t v) const { return isPushed_[v]; }
bool isPopped(vertex_index_t v) const { return isPopped_[v]; }
private:
graph_type& graph_;
// 待处理的邻接顶点迭代器
std::queue<adj_vertex_iter> todo_;
vertex_index_t v0_; // 起始顶点
std::vector<bool> isPushed_, isPopped_; // 用于标记顶点是否已压栈/出栈
};
|
koala999cn/kGraph
|
src/core/KtShortestPath.h
|
#pragma once
#include <vector>
#include "KtWeightor.h"
#include "KtBfsIter.h"
#include "KtDfsIter.h"
#include "KtTopologySort.h"
// 最短路径算法
// 此类算法的关键是顶点处理的顺序,对应有顺序遍历、Dfs、Bfs、Pfs、Ts等方法。
// 不同实现的时间复杂度如下:
// 单源:
// Dijkstra,适用于非负权值,O(V^2),稠密图最优
// PFS,适用于非负权值,O(E*lgV),保守边界值
// TS,适用于无环图,O(E),最优
// Bellman-Ford,适用于无负环图,O(V*E),有改进余地吗?
// 全源:
// Dijkstra,适用于非负权值,O(V^3),对所有图均相同
// PFS,适用于非负权值,O(V*E*lgV),保守边界值
// DFS,适用于无环图,O(V*E),对所有图均相同
// Floyd,适用于无负环图,O(V^3),对所有图均相同
// Johnson,适用于无负环图,O(V*E*lgV),保守边界值
// 注:由于权值的零值和偏移转换难以统一,Johnson尚未实现
// 单源最短路径的基类:计算起始顶点v0(源点)到图g中其他各顶点的最短路径
template<typename GRAPH, class WEIGHTOR, bool tracePath = true>
class KtSptAbstract
{
static_assert(GRAPH::isDigraph(), "KtSptAbstract must be instantiated with Digraph.");
public:
using weight_type = typename WEIGHTOR::weight_type;
using vertex_index_t = typename GRAPH::vertex_index_t;
KtSptAbstract(const GRAPH& g, vertex_index_t v0) :
v0_(v0),
spt_(g.order(), -1),
dist_(g.order(), WEIGHTOR{}.worst_weight) {}
// 返回从源点到顶点v的最短路径(逆序)
auto pathR(vertex_index_t v) const {
std::vector<vertex_index_t> p;
vertex_index_t s = v;
do {
p.push_back(s);
s = spt_[s];
} while (s != v0_ && s != v && s != -1);
// s == -1,表示没有环路,路径入栈成功
// s == v0,表示v0存在环路,需要手动将v0入栈
// s == v,表示存在经过v的负环,这时丢失了从v0->v的最短路径,栈中路径退化为以v为起止点的负环。
if(s != -1) p.push_back(s);
return p;
}
// 返回从源点到顶点v的最短距离
weight_type distance(vertex_index_t v) const {
return dist_[v];
}
// 是否存在从源点到v的路径
bool reachable(vertex_index_t v) const {
return spt_[v] != -1;
}
protected:
// 边松弛. 判断v0经过边(v, w)到w的路径是否比当前到w的路径更好
// wt为边(v, w)的权值
bool relax_(vertex_index_t v, vertex_index_t w, weight_type wt) {
if (spt_[v] != -1) {
if (v != v0_)
wt = WEIGHTOR{}.acc(wt, dist_[v]);
}
else if (v != v0_)
return false;
if(WEIGHTOR{}.comp(wt, dist_[w])) {
dist_[w] = wt, spt_[w] = v;
return true;
}
return false;
}
protected:
vertex_index_t v0_; // 源点
std::vector<vertex_index_t> spt_; // (spt_[i], i)表示从源点v0_到顶点i的最短路径上的最后一条边
std::vector<weight_type> dist_; // dist_[i]表示从源点v0_到顶点i的最短距离
};
// 基于广度优先搜索的单源最短路径实现
// 处理E较大的有环图时,速度非常慢
// 处理DAG较有优势,貌似比TS方法还快
// NOTE: 当有负环的时候,会陷入无限递归
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtSptBfs : public KtSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
public:
KtSptBfs(const GRAPH& g, vertex_index_t v0) :super_(g, v0) {
bfs_(g, v0);
}
private:
void bfs_(const GRAPH& g, vertex_index_t v) {
KtBfsIter<const GRAPH, false, true> iter(g, v);
for (; !iter.isEnd(); ++iter) {
vertex_index_t v = iter.from(), w = *iter;
// 如果relax_更新了已出栈的顶点信息,则需要对出栈顶点重新bfs
if (super_::relax_(v, w, WEIGHTOR{}(iter.edge())) && iter.isPopped(w))
bfs_(g, w);
}
}
};
// 速度比bfs还慢,慢很多,弃疗
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtSptDfs : public KtSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
public:
KtSptDfs(const GRAPH& g, vertex_index_t v0) : super_(g, v0) {
dfs_(g, v0);
}
private:
void dfs_(const GRAPH& g, vertex_index_t v) {
KtDfsIter<const GRAPH, false, true> iter(g, v);
for (; !iter.isEnd(); ++iter) {
vertex_index_t v = iter.from(), w = *iter;
if (super_::relax_(v, w, WEIGHTOR{}(iter.edge())))
if (!iter.isTree() && w != v)
dfs_(g, w); // TODO: 区分不同类型的边(跨边,下边,回边),进一步优化
}
}
};
// 基于Dijkstra算法的单源最短路径实现
// NOTE: 该算法不支持负环,也不支持负权值,因为一旦出现负权值,
// 可能会出现一条比之前更短的路径,这会破坏始终延着最短路径生长的准则
// 也就是说,我们无法判断当前的最短路径是不是真的最短,因为后面出现的负权值可能会让其他路径更短
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtSptDijkstra : public KtSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
using super_::spt_;
using super_::dist_;
public:
KtSptDijkstra(const GRAPH& g, vertex_index_t v0) : super_(g, v0) {
std::vector<bool> vis(g.order(), false); // 用于标记源点v0到顶点i的最短路径是否已计算
vertex_index_t v = v0;
while (v != -1) {
vis[v] = true;
// 边松弛
for (vertex_index_t w = 0; w < g.order(); w++)
if ((!vis[w] || w == v0/*permit loop path*/) && g.hasEdge(v, w))
super_::relax_(v, w, WEIGHTOR{}(g.getEdge(v, w)));
// 在vis[i]等于false的集合中,寻找距离v0路径最优的顶点. TODO: 使用优先队列实现
v = -1;
for (vertex_index_t w = 0; w < g.order(); w++)
if (!vis[w] && (v == -1 || WEIGHTOR{}.comp(dist_[w], dist_[v])))
v = w;
if (v == -1 || spt_[v] == -1/*disconnecte to v0*/) break; // all done
}
}
};
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtSptPfs : public KtSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
using super_::dist_;
public:
KtSptPfs(const GRAPH& g, vertex_index_t v0) : super_(g, v0) {
using element_type = std::pair<vertex_index_t, typename WEIGHTOR::weight_type>;
struct Comp {
bool operator()(const element_type& a, const element_type& b) {
return WEIGHTOR{}.comp(b.second, a.second); // 优先队列的比较函数需要反过来比较,才能保证最优元素在队列顶端
}
};
using priority_queue = std::priority_queue<element_type, std::vector<element_type>, Comp>;
priority_queue pq; pq.emplace(v0, dist_[v0]);
std::vector<bool> vis(g.order(), false); // 用于标记源点v0到顶点i的最短路径是否已计算
while (!pq.empty()) {
auto v = pq.top().first; pq.pop();
if (vis[v]) continue;
vis[v] = true;
// 边松弛
for (vertex_index_t w = 0; w < g.order(); w++)
if ((!vis[w] || w == v0/*permit loop path*/) && g.hasEdge(v, w))
if (super_::relax_(v, w, WEIGHTOR{}(g.getEdge(v, w))))
pq.emplace(w, dist_[w]);
}
}
};
// 基于拓扑排序算法的单源最短路径实现,仅适用于DAG.
// 运行速度没有想像中快,效率还比不上bfs方法
template<typename DAG, class WEIGHTOR = default_wtor<DAG>>
class KtSptTs : public KtSptAbstract<DAG, WEIGHTOR>
{
using super_ = KtSptAbstract<DAG, WEIGHTOR>;
using typename super_::vertex_index_t;
public:
KtSptTs(const DAG& g, vertex_index_t v0) : super_(g, v0) {
assert(!has_loop(g));
KtTopologySort<DAG> ts(g);
auto j = ts.relabel(v0); // j之前的顶点可以忽略,因为按照拓扑排序,v0与它们没有可达路径
for(auto v = ts[j++]; j < g.order(); v = ts[j++]) {
auto iter = KtAdjIter(g, v);
while(!iter.isEnd()) {
super_::relax_(v, *iter, WEIGHTOR{}(iter.edge()));
++iter;
}
}
}
};
// 基于Bellman-Ford算法的单源最短路径实现
// NOTE: 可用来解决包含负权值的单源最短路径问题,时间复杂度O(VE)。
// 对于稠密图,其运行时间不比Floyd算法更好,Floyd算法则要找出全部最短路径,而不仅仅是单源。
// 对于稀疏图,其运行时间最多比Floyd算法快V倍,但对于无负权值的图,其运行时间比Dijkstra算法慢约V倍。
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtSptBellmanFord : public KtSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
public:
KtSptBellmanFord(const GRAPH& g, vertex_index_t v0) : super_(g, v0) {
std::queue<vertex_index_t> q;
unsigned V = g.order();
q.push(v0); q.push(V); // 标记值V将当前一批顶点与下一批顶点分隔,并使得可以在V遍处理后终止。
unsigned N = 0;
while (!q.empty()) {
vertex_index_t v = q.front(); q.pop();
while (v == V) {
if (N++ > V) return; // 存在一条长度超过V的最短路径,这表示肯定存在负环。
q.push(V);
v = q.front(); q.pop();
}
auto iter = KtAdjIter(g, v);
for (; !iter.isEnd(); ++iter)
if (super_::relax_(v, *iter, WEIGHTOR{}(iter.edge()))
&& *iter != v/*ignore self-loop*/)
q.push(*iter);
}
}
};
// 全源最短路径的基类:计算任意顶点到图中其他各顶点的最短路径
template<typename GRAPH, class WEIGHTOR>
class KtAllSptAbstract
{
static_assert(GRAPH::isDigraph(), "KtAllSptAbstract must be instantiated with Digraph.");
public:
using weight_type = typename WEIGHTOR::weight_type;
using vertex_index_t = typename GRAPH::vertex_index_t;
KtAllSptAbstract(const GRAPH& g)
: spt_(g.order(), std::vector<vertex_index_t>(g.order(), -1)),
dst_(g.order(), std::vector<weight_type>(g.order(), WEIGHTOR{}.worst_weight)) {}
weight_type distance(vertex_index_t v, vertex_index_t w) const {
return dst_[v][w];
}
// 返回v到w的最短路径(逆序)
auto pathR(vertex_index_t v, vertex_index_t w) const {
std::vector<vertex_index_t> p;
vertex_index_t s = w;
do {
p.push_back(s);
s = spt_[v][s];
} while (s != v && s != w && s != -1 );
if (s != -1) p.push_back(s);
return p;
}
protected:
// 路径松弛. 判断s经过x再到t的路径是否比当前s到t的路径更好
bool relax_(vertex_index_t s, vertex_index_t t, vertex_index_t x) {
assert(x != s && x != t); // s可能等于t,用于计算最短环路
const auto dst = WEIGHTOR{}.acc(dst_[s][x], dst_[x][t]);
if (WEIGHTOR{}.comp(dst, dst_[s][t])) { // dst比dst_[s][t]更优
dst_[s][t] = dst;
spt_[s][t] = spt_[x][t];
return true;
}
return false;
}
protected:
template<typename T> using vector = std::vector<T>;
vector<vector<vertex_index_t>> spt_;
vector<vector<weight_type>> dst_;
};
// Floyd实现全源最短路径
// 时间复杂度O(V^3),适用于稠密图
// 对于稀疏图,可逐个顶点用Dijkstra算法计算单源最短路径,从而得到全源最短路径
// NOTE: 该算法未对权值作任何假设,因此即使存在负权值也是有效的。
// 如果不存在负环,则会计算出最短路径;否则,只能找出一条不包过负环的最短路径。
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtAllSptFloyd : public KtAllSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtAllSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
using super_::spt_;
using super_::dst_;
public:
KtAllSptFloyd(const GRAPH& g) : super_(g) {
// 按边初始化spt_和dst_
KtBfsIter<const GRAPH, true, true> iter(g, 0);
for (; !iter.isEnd(); ++iter) {
vertex_index_t v = iter.from(), w = *iter;
spt_[v][w] = v;
dst_[v][w] = WEIGHTOR{}(iter.edge());
}
const vertex_index_t V = g.order();
// 判定路径s->x->t是否比路径s->t更优
for (vertex_index_t x = 0; x < V; x++)
for (vertex_index_t s = 0; s < V; s++)
if (spt_[s][x] != -1 && s != x) // 若s->x不通,或者s==x,则略过
for (vertex_index_t t = 0; t < V; t++)
if(t != x) super_::relax_(s, t, x);
}
};
// DFS实现全源最短路径,仅适用于DAG
// 时间复杂度O(V*E)
// 速度比TS方法快很多
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtAllSptDfs : public KtAllSptAbstract<GRAPH, WEIGHTOR>
{
using super_ = KtAllSptAbstract<GRAPH, WEIGHTOR>;
using typename super_::vertex_index_t;
using super_::spt_;
using super_::dst_;
public:
KtAllSptDfs(const GRAPH& g) : super_(g), done_(g.order(), false) {
assert(!has_loop(g));
for (vertex_index_t v = 0; v < g.order(); v++)
if(!done_[v]) dfs_(g, v);
}
private:
void dfs_(const GRAPH& g, vertex_index_t v) {
done_[v] = true;
auto iter = KtAdjIter(g, v);
for (; !iter.isEnd(); ++iter) {
auto w = *iter;
auto wt = WEIGHTOR{}(iter.edge());
if (WEIGHTOR{}.comp(wt, dst_[v][w])) {
dst_[v][w] = wt;
spt_[v][w] = v;
}
if (!done_[w]) dfs_(g, w);
if (w != v) {
for (vertex_index_t i = 0; i < g.order(); i++)
if (spt_[w][i] != -1 && w != i)
super_::relax_(v, i, w);
}
}
}
private:
std::vector<bool> done_;
};
|
koala999cn/kGraph
|
src/util/dump.h
|
<gh_stars>0
#include <ostream>
#include "../base/traits_helper.h"
// dump graph "g" to file "path"
template<typename GRAPH>
void dump(const GRAPH& g, std::ostream& os)
{
auto V = static_cast<unsigned>(g.order());
for (unsigned i = 0; i < V; i++) {
unsigned jMin = g.isDigraph() ? 0 : i;
for (unsigned j = jMin; j < V; j++) {
auto r = g.edges(i, j);
if (r.empty())
continue;
os << "(" << i << ", " << j;
if constexpr (has_operator_output<decltype(os), decltype(r)>::value)
for (; !r.empty(); ++r)
os << ", " << *r;
os << ") ";
}
os << "\n";
}
}
|
koala999cn/kGraph
|
src/core/KtWeightor.h
|
<gh_stars>0
#pragma once
#include <limits>
#undef max
// 与权值有关的操作:包括从边值到权值的转换,权值的比较,权值的累加
template<typename VALUE_TYPE>
class KtWeightSelf
{
public:
using weight_type = VALUE_TYPE;
weight_type operator()(const VALUE_TYPE& val) const {
return val;
}
};
template<typename VALUE_TYPE>
class KtWeightUnit
{
public:
using weight_type = int;
constexpr weight_type operator()(const VALUE_TYPE&) const {
return 1;
}
};
template<typename WEIGHT_TYPE>
class KtAdder
{
public:
auto operator()(const WEIGHT_TYPE& w1, const WEIGHT_TYPE& w2) const {
return w1 + w2;
}
};
// @minimum:为true时则小值更优,否则大值更优。
template<class WeightorBase, class Accumlate, bool minimum>
class KtWeightor : public WeightorBase
{
public:
using weight_type = typename WeightorBase::weight_type;
const weight_type worst_weight = minimum ?
std::numeric_limits<weight_type>::max() :
std::numeric_limits<weight_type>::lowest();
// w1是否比w2更优?
bool comp(const weight_type& w1, const weight_type& w2) const {
return minimum ? w1 < w2 : w1 > w2;
}
// 权值累加
auto acc(const weight_type& w1, const weight_type& w2) const {
return Accumlate{}(w1, w2);
}
};
template<class WeightorBase, class Accumlate>
using KtWeightorMin = KtWeightor<WeightorBase, Accumlate, true>;
template<class WeightorBase, class Accumlate>
using KtWeightorMax = KtWeightor<WeightorBase, Accumlate, false>;
template<typename GRAPH>
using default_min_wtor = KtWeightorMin<KtWeightSelf<typename GRAPH::edge_type>, KtAdder<typename KtWeightSelf<typename GRAPH::edge_type>::weight_type>>;
template<typename GRAPH>
using default_max_wtor = KtWeightorMax<KtWeightSelf<typename GRAPH::edge_type>, KtAdder<typename KtWeightSelf<typename GRAPH::edge_type>::weight_type>>;
template<typename GRAPH>
using unit_min_wtor = KtWeightorMin<KtWeightUnit<typename GRAPH::edge_type>, KtAdder<typename KtWeightUnit<typename GRAPH::edge_type>::weight_type>>;
template<typename GRAPH>
using unit_max_wtor = KtWeightorMax<KtWeightUnit<typename GRAPH::edge_type>, KtAdder<typename KtWeightUnit<typename GRAPH::edge_type>::weight_type>>;
template<typename GRAPH>
using default_wtor = default_min_wtor<GRAPH>;
|
koala999cn/kGraph
|
src/util/randgen.h
|
<filename>src/util/randgen.h
#pragma once
#include <cmath>
#include "../core/KtGraph.h"
// 返回[x0, x1]区间的随机数
inline double rand(double x0, double x1)
{
return x0 + (x1 - x0) * rand() / RAND_MAX;
}
// 以p的概率返回true.
// 0 <= p <= 1
inline bool rand_p(double p)
{
return rand() <= RAND_MAX * p;
}
template<typename GRAPH>
GRAPH randgen(unsigned V, unsigned E)
{
GRAPH g(V);
double p = static_cast<double>(E) / (V * V);
if (!g.isDigraph()) p *= 2; // 对于无向图,边的生成概率翻倍
for (unsigned i = 0; i < V; i++) {
unsigned jMax = g.isDigraph() ? V : i + 1;
for (unsigned j = 0; j < jMax; j++)
if (rand_p(p)) {
unsigned numEdges(1);
if constexpr (g.isMultiEdges())
numEdges = rand() % 6 + 1;
for (unsigned c = 0; c < numEdges; c++) {
int r = 0;
while (r == 0) r = rand();
using edge_type = typename GRAPH::edge_type;
edge_type val(std::is_floating_point<edge_type>::value ? edge_type(r) / RAND_MAX : r);
g.addEdge(i, j, val);
}
}
}
if constexpr (!std::is_void_v<typename GRAPH::vertex_type>)
for (unsigned v = 0; v < g.order(); v++) {
if constexpr (std::is_floating_point<typename GRAPH::vertex_type>::value)
g.vertexAt(v) = float(rand()) / RAND_MAX;
else if constexpr (std::is_convertible_v<int, typename GRAPH::vertex_type>)
g.vertexAt(v) = rand();
}
return g;
}
|
koala999cn/kGraph
|
src/util/is_same.h
|
#pragma once
#include <algorithm>
#include "../core/graph_traits.h"
// 判断两个图g1、g2的拓扑结构是否相同,不对顶点对象进行比较
// 假定顶点顺序一致
template<typename G1, typename G2>
bool is_topo_same(const G1& g1, const G2& g2)
{
if (g1.order() != g2.order() || g1.size() != g2.size())
return false;
for (unsigned v = 0; v < g1.order(); v++) {
for (unsigned w = 0; w < g1.order(); w++) {
auto edges1 = g1.edges(v, w);
auto edges2 = g2.edges(v, w);
if (edges1.size() != edges2.size())
return false;
std::vector<typename G1::edge_type> e1;
std::vector<typename G2::edge_type> e2;
while (!edges1.empty()) {
e1.push_back(*edges1);
e2.push_back(*edges2);
++edges1, ++edges2;
}
if constexpr (!g1.isAlwaysSorted())
std::sort(e1.begin(), e1.end());
if constexpr (!g2.isAlwaysSorted())
std::sort(e2.begin(), e2.end());
for (size_t i = 0; i < e1.size(); i++)
if (e1[i] != e2[i])
return false;
}
}
return true;
}
template<typename G1, typename G2>
bool is_same(const G1& g1, const G2& g2)
{
// 先比较顶点对象
if constexpr (!std::is_same_v<graph_traits<G1>::vertex_type, graph_traits<G2>::vertex_type>)
return false;
if constexpr (!std::is_void_v<graph_traits<G1>::vertex_type>) {
for (unsigned v = 0; v < g1.order(); v++)
if (g1.vertexAt(v) != g2.vertexAt(v))
return false;
}
// 再比较拓扑结构
return is_topo_same(g1, g2);
}
|
koala999cn/kGraph
|
test/test_util.h
|
<gh_stars>0
#pragma once
#include <fstream>
#include <string>
#include <vector>
#include "../src/util/dump.h"
// dump graph "g" to file "path"
template<typename GRAPH>
void dump(const GRAPH& g, const char* path)
{
std::ofstream of(path);
dump(g, of);
}
// 测试失败时调用该函数打印信息、退出程序
template<typename GRAPH>
void test_failed(const GRAPH& g, bool detail = false)
{
printf(" > :( failed\n");
printf(" dumping failed graph to 'graph_dump.txt'...\n");
dump(g, "graph_dump.txt");
printf("press any key to exit.\n");
fflush(stdout);
getchar();
exit(1);
}
template<typename G1, typename G2>
void test_failed(const G1& g1, const G2& g2)
{
printf(" > :( failed\n");
printf(" dumping failed graph to 'graph_dump1.txt & graph_dump2.txt'...\n");
dump(g1, "graph_dump1.txt");
dump(g2, "graph_dump2.txt");
printf("press any key to exit.\n");
fflush(stdout);
getchar();
exit(1);
}
bool almostEqual(double x1, double x2, double tol = 1e-10);
// dump the pathR to string
std::string format_pathR(const std::vector<unsigned>& pathR);
|
koala999cn/kGraph
|
src/base/KtRange.h
|
<reponame>koala999cn/kGraph<gh_stars>0
#pragma once
#include <algorithm>
template<typename ITER_TYPE>
class KtRange
{
public:
using iterator = ITER_TYPE;
using const_iterator = ITER_TYPE; // std::add_const_t<iterator>;
using element_type = decltype(*std::declval<iterator>());
using const_element_type = std::add_const_t<element_type>;
using value_type = std::decay_t<element_type>;
constexpr static bool is_const = std::is_const_v<element_type>;
KtRange() = default;
KtRange(const KtRange&) = default;
KtRange(KtRange&&) = default;
KtRange& operator=(const KtRange&) = default;
KtRange& operator=(KtRange&&) = default;
KtRange(const iterator& first, const iterator& last) :
first_(first), last_(last) {}
KtRange(const iterator& first, unsigned count) :
first_(first), last_(std::next(first, count)) {}
void reset(const iterator& first, const iterator& last) {
first_ = first, last_ = last;
}
bool operator==(const KtRange& rhs) const {
return first_ == rhs.first_ && last_ == rhs.last_;
}
bool operator!=(const KtRange& rhs) const {
return first_ != rhs.first_ || last_ != rhs.last_;
}
// 作为容器使用
iterator begin() { return first_; }
iterator end() { return last_; }
const_iterator begin() const { return first_; }
const_iterator end() const { return last_; }
const_iterator cbegin() const { return first_; }
const_iterator cend() const { return last_; }
auto size() const { return std::distance(first_, last_); }
auto front() { return *first_; }
auto front() const { return *first_; }
auto back() { return *(last_ - 1); }
auto back() const { return *(last_ - 1); }
decltype(auto) at(unsigned idx) { return *std::next(first_, idx); }
decltype(auto) at(unsigned idx) const { return *std::next(first_, idx); }
KtRange subrange(unsigned offset, unsigned count) const {
if (offset > size()) offset = size();
if (offset + count > size()) count = size() - offset;
return KtRange(std::next(first_, offset), count);
}
KtRange first(unsigned count) const {
return subrange(0, count);
}
KtRange last(unsigned count) const {
return subrange(size() - count, count);
}
// 作为迭代器使用
iterator& operator++() { return ++first_; }
void advance(unsigned n) { std::advance(first_, n); }
decltype(auto) operator*() { return *first_; }
decltype(auto) operator*() const { return *first_; }
bool empty() const { return first_ == last_; }
// advance first_ until Pred(first_)
template<typename Pred>
void skipUntil(Pred pred) {
while (!empty() && !pred(first_))
++first_;
}
// 对一些常用std算法的封装
void sort() { std::sort(first_, last_); }
template<class Compare> void sort(Compare comp) { std::sort(first_, last_, comp); }
void reverse() { std::reverse(first_, last_); }
void fill(const value_type& val) { std::fill(first_, last_, val); }
auto count(const value_type& val) const { return std::count(first_, last_, val); }
private:
iterator first_, last_;
};
|
koala999cn/kGraph
|
src/GraphX.h
|
<filename>src/GraphX.h
#pragma once
#include "core/KtAdjGraphDenseImpl.h"
#include "core/KtAdjGraphSparseImpl.h"
#include "core/KtFlatGraphVectorImpl.h"
#include "core/KtGraph.h"
#include "core/KtAdjIter.h"
#include "core/KtBfsIter.h"
#include "core/KtDfsIter.h"
#include "core/KtPfsIter.h"
// 对一些常用迭代器的封装
template<typename GRAPH>
class KtGraphX : public GRAPH
{
public:
using super_ = GRAPH;
using graph_type = GRAPH;
using const_graph_type = std::add_const_t<graph_type>;
using adj_iter = KtAdjIter<graph_type>;
using const_adj_iter = KtAdjIter<const_graph_type>;
template<bool fullGraph, bool modeEdge>
using bfs_iter = KtBfsIter<graph_type, fullGraph, modeEdge>;
template<bool fullGraph, bool modeEdge>
using const_bfs_iter = KtBfsIter<const_graph_type, fullGraph, modeEdge>;
template<bool fullGraph, bool modeEdge, bool stopAtPopping>
using dfs_iter = KtDfsIter<graph_type, fullGraph, modeEdge, stopAtPopping>;
template<bool fullGraph, bool modeEdge, bool stopAtPopping>
using const_dfs_iter = KtDfsIter<const_graph_type, fullGraph, modeEdge, stopAtPopping>;
using edge_iter = bfs_iter<true, true>;
using const_edge_iter = const_bfs_iter<true, true>;
using typename super_::vertex_index_t;
using super_::super_;
auto adjIter(vertex_index_t s) {
return adj_iter(*this, s);
}
auto adjIter(vertex_index_t s) const {
return const_adj_iter(*this, s);
}
template<bool fullGraph, bool modeEdge>
auto bfsIter(vertex_index_t s) {
retrn bfs_iter<fullGraph, modeEdge>(*this, s);
}
template<bool fullGraph, bool modeEdge>
auto bfsIter(vertex_index_t s) const {
retrn const_bfs_iter<fullGraph, modeEdge>(*this, s);
}
template<bool fullGraph, bool modeEdge, bool stopAtPopping>
auto dfsIter(vertex_index_t s) {
retrn dfs_iter<fullGraph, modeEdge, stopAtPopping>(*this, s);
}
template<bool fullGraph, bool modeEdge, bool stopAtPopping>
auto dfsIter(vertex_index_t s) const {
retrn const_dfs_iter<fullGraph, modeEdge, stopAtPopping>(*this, s);
}
auto edgeIter() {
return edge_iter(*this, 0);
}
auto edgeIter() const {
return const_edge_iter(*this, 0);
}
};
/// 稠密无向图
template<typename EDGE_TYPE, typename VERTEX_TYPE = void>
using GraphDx = KtGraphX<KtGraph<KtAdjGraphDenseImpl<EDGE_TYPE, VERTEX_TYPE>, false, false, false>>;
using GraphDi = GraphDx<int>;
using GraphDd = GraphDx<double>;
using GraphDf = GraphDx<float>;
/// 稠密有向图
template<typename EDGE_TYPE, typename VERTEX_TYPE = void>
using DigraphDx = KtGraphX<KtGraph<KtAdjGraphDenseImpl<EDGE_TYPE, VERTEX_TYPE>, true, false, false>>;
using DigraphDi = DigraphDx<int>;
using DigraphDd = DigraphDx<double>;
using DigraphDf = DigraphDx<float>;
/// 稀疏无向图
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using GraphSx = KtGraphX<KtGraph<KtAdjGraphSparseImpl<EDGE_TYPE, VERTEX_TYPE>, false, false, alwaysSorted>>;
template<bool alwaysSorted = false>
using GraphSi = GraphSx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphSd = GraphSx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphSf = GraphSx<float, void, alwaysSorted>;
/// 稀疏有向图
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using DigraphSx = KtGraphX<KtGraph<KtAdjGraphSparseImpl<EDGE_TYPE, VERTEX_TYPE>, true, false, alwaysSorted>>;
template<bool alwaysSorted = false>
using DigraphSi = DigraphSx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphSd = DigraphSx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphSf = DigraphSx<float, void, alwaysSorted>;
/// 平行无向图(允许重边/平行边)
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using GraphPx = KtGraphX<KtGraph<KtAdjGraphSparseImpl<EDGE_TYPE, VERTEX_TYPE>, false, true, alwaysSorted>>;
template<bool alwaysSorted = false>
using GraphPi = GraphPx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphPd = GraphPx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphPf = GraphPx<float, void, alwaysSorted>;
/// 平行有向图(允许重边/平行边)
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using DigraphPx = KtGraphX<KtGraph<KtAdjGraphSparseImpl<EDGE_TYPE, VERTEX_TYPE>, true, true, alwaysSorted>>;
template<bool alwaysSorted = false>
using DigraphPi = DigraphPx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphPd = DigraphPx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphPf = DigraphPx<float, void, alwaysSorted>;
/// 扁平无向图(允许重边/平行边)
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using GraphFx = KtGraphX<KtGraph<KtFlatGraphVectorImpl<EDGE_TYPE, VERTEX_TYPE>, false, true, alwaysSorted>>;
template<bool alwaysSorted = false>
using GraphFi = GraphFx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphFd = GraphFx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using GraphFf = GraphFx<float, void, alwaysSorted>;
/// 扁平有向图(允许重边/平行边)
template<typename EDGE_TYPE, typename VERTEX_TYPE = void, bool alwaysSorted = false>
using DigraphFx = KtGraphX<KtGraph<KtFlatGraphVectorImpl<EDGE_TYPE, VERTEX_TYPE>, true, true, alwaysSorted>>;
template<bool alwaysSorted = false>
using DigraphFi = DigraphFx<int, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphFd = DigraphFx<double, void, alwaysSorted>;
template<bool alwaysSorted = false>
using DigraphFf = DigraphFx<float, void, alwaysSorted>;
|
koala999cn/kGraph
|
src/core/KtMaxFlow.h
|
<gh_stars>0
#pragma once
#include <vector>
#include <assert.h>
#include "KtWeightor.h"
#include "KtShortestPath.h"
#include "KtBfsIter.h"
#include "../util/copy.h"
#include "../GraphX.h"
// 最大流:给定一个st-网,找出一个流,从而使得从s到t的任何其他流都不会有更大的流值。
// 主要有两大类算法:一是扩充路径最大流算法,二是预流-压入最大流算法
// 以上两大类算法均依赖于【余留网(residual network)】:给定一个流网络和一个流,流的余留网有着原网相同的顶点,
// 对于原网中的各条边,余留网中将有1条或2条边,有如下定义:对于原网中的各条边v-w,
// 令f为流量,c为容量, 那么:
// ①如果f != c,则在余留网中包括一条容量为c-f的前边v-w;(代表余留量,即该条边还可扩充或压入的流量)
// ②如果f != 0,则在余留网中包括一条容量为f的回边w-v。(代表当前量,即该条边已有的流量,也即可回退的流量)
// 最大流的基类,实现余留网基本操作
template<typename GRAPH, typename WEIGHTOR>
class KtMaxFlow
{
protected:
using flow_type = typename WEIGHTOR::weight_type;
using RGRAPH = DigraphSx<flow_type>; // 余留网类型
static_assert(std::is_integral_v<flow_type>, "max flow algorithm only support integral weight");
// 对输入g的限制:
// 1. g为st网,即有且仅有1个源点、1个汇点;
// 2. 若v-w为g的边,则w-v不能是g的边。
KtMaxFlow(const GRAPH& g, unsigned s, unsigned t)
: graph_(g), // 保存原图引用
rg_(copy<GRAPH, RGRAPH, WEIGHTOR>(g)) { // 构造余留网
assert(s != t);
}
public:
// 返回边v-w的网容量
auto cap(unsigned v, unsigned w) const {
return WEIGHTOR{}(graph_.getEdge(v, w));
}
// 返回边v-w的网流量
auto flow(unsigned v, unsigned w) const {
assert(graph_.hasEdge(v, w));
return rg_.hasEdge(w, v) ? rg_.getEdge(w, v) : 0;
}
// 返回边v-w的余留量 := cap - flow
auto residual(unsigned v, unsigned w) const {
assert(graph_.hasEdge(v, w));
return rg_.hasEdge(v, w) ? rg_.getEdge(v, w) : 0;
}
// 返回顶点v的流出量
auto outflow(unsigned v) const {
flow_type f(0);
auto iter = KtAdjIter(graph_, v);
for (; !iter.isEnd(); ++iter)
f += flow(v, *iter);
return f;
}
// 返回顶点v的流入量
auto inflow(unsigned v) const {
flow_type f(0);
for (unsigned w = 0; w < graph_.order(); w++)
if (graph_.hasEdge(w, v))
f += flow(w, v);
return f;
}
// 返回顶点v的净流量 = 流入量 - 流出量
auto netflow(unsigned v) const {
return inflow(v) - outflow(v);
}
bool check(unsigned s, unsigned t) const {
if (outflow(s) != inflow(t))
return false;
for (unsigned v = 0; v < graph_.order(); v++)
if (v != s && v != t && netflow(v) != 0)
return false;
return true;
}
protected:
// 对余留网的边v-w增加网流delta
void addFlow_(unsigned v, unsigned w, flow_type delta) {
assert(rg_.hasEdge(v, w));
flow_type f = rg_.getEdge(v, w);
f -= delta; // 该条边的可增广流量减少delta
if (f == 0)
rg_.eraseEdge(v, w);
else
rg_.setEdge(v, w, f);
// 对应回边的可增广流量增加delta
if (rg_.hasEdge(w, v))
rg_.setEdge(w, v, rg_.getEdge(w, v) + delta);
else
rg_.addEdge(w, v, delta);
}
protected:
const GRAPH& graph_; // 原图
RGRAPH rg_; // 余留网
};
// 扩充路径最大流算法的基类
// 扩充路径最大流算法也称Ford-Fulkerson算法
// 这是一种沿着从源点到汇点的路径逐渐增加流的通用方法
// 对于任意无满的前边且无空的回边的路径,可以通过增加前边中的流,同时减少回边中的流来增加网中的流量。
// 可以增加的流量由回边中的流和前边中未用容量的最小值所限制。
// 在新的流中,至少路径上有一条前边被充满,或者有一条回边变为空。
// 简而言之,余留网的边权值就是可增广的流量值,在余留网中搜索s到t的路径,即为增广路径。
// 增广路径搜索算法常见有2种:
// 一是最大容量扩充路径,即沿着可以使流得到最大增长的路径扩充。
// 二是最短扩充路径,即即沿着边数最少的路径扩充。
// Ford-Fulkerson算法任何实现所需的扩充路径数目最多等于V*M,
// 找出一个最大流所需时间为O(V*E*M),对于稀疏网则为O(V^2*M)。其中,M为网中最大的边容量。
template<typename GRAPH, class WEIGHTOR>
class KtPathAugment : public KtMaxFlow<GRAPH, WEIGHTOR>
{
protected:
using super_ = KtMaxFlow<GRAPH, WEIGHTOR>;
using super_::super_; // 导入构造函数
using super_::rg_;
using super_::addFlow_;
using typename super_::flow_type;
using typename super_::RGRAPH;
protected:
// 返回余留网逆路径pathR的可增广网络流:路径上的最小边
flow_type minFlow_(const std::vector<unsigned>& pathR) const {
auto iter = pathR.begin();
unsigned w = *iter++;
unsigned v = *iter++;
flow_type d = rg_.getEdge(v, w);
while (iter != pathR.end()) {
w = v;
v = *iter++;
flow_type x = rg_.getEdge(v, w);
if (x < d) d = x;
}
return d;
}
// 对逆路径pathR进行增广
void augment_(const std::vector<unsigned>& pathR, flow_type delta) {
// 沿着路径增广delta
auto iter = pathR.begin();
auto w = *iter++;
unsigned v;
for (; iter != pathR.end(); w = v, ++iter) {
v = *iter;
addFlow_(v, w, delta);
}
}
};
// 基于优先队列搜索的最大容量扩充路径算法
// 该算法所需的扩充路径数目最多等于2*E*lgM,找出稀疏网中一个最大流所需时间为O(V^2*lgM*lgV)。
// 对许多实际情况,最大容量扩充路径算法所用的迭代远远小于最短扩充路径算法所用的迭代,
// 不过对于找到各条路径的工作则需要一个稍高的开销。
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtMaxFlowPfs : public KtPathAugment<GRAPH, WEIGHTOR>
{
public:
using super_ = KtPathAugment<GRAPH, WEIGHTOR>;
using super_::rg_;
using super_::augment_;
using super_::minFlow_;
using typename super_::flow_type;
using typename super_::RGRAPH;
KtMaxFlowPfs(const GRAPH& g, unsigned s, unsigned t) : super_(g, s, t) {
// 可增广流量为路径上的最小值
struct adder {
auto operator()(const flow_type& f1, const flow_type& f2) const {
return std::min(f1, f2);
}
};
// 取可增广流量最大的路径
using weightor = KtWeightorMax<KtWeightSelf<flow_type>, adder>;
while (true) {
KtSptPfs<RGRAPH, weightor> pfs(rg_, s);
auto path = pfs.pathR(t);
if (path.size() < 2)
break;
assert(path.back() == s && path.front() == t);
// 增广路径,更新余留网的权值
assert(pfs.distance(t) == minFlow_(path));
augment_(path, pfs.distance(t));
}
}
};
// 基于广度优先搜索的最短扩充路径算法,也称Edmonds-Karp算法
// 该算法所需的扩充路径数目最多等于V*E/2,找出稀疏网中一个最大流所需时间为O(V^3)。
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtMaxFlowBfs : public KtPathAugment<GRAPH, WEIGHTOR>
{
public:
using super_ = KtPathAugment<GRAPH, WEIGHTOR>;
using super_::rg_;
using super_::augment_;
using super_::minFlow_;
using typename super_::flow_type;
using typename super_::RGRAPH;
KtMaxFlowBfs(const GRAPH& g, unsigned s, unsigned t) : super_(g, s, t) {
// 取边数最少的路径
using weightor = KtWeightorMin<KtWeightUnit<flow_type>, KtAdder<typename KtWeightUnit<flow_type>::weight_type>>;
while (true) {
KtSptPfs<RGRAPH, weightor> bfs(rg_, s);
auto path = bfs.pathR(t);
if (path.size() < 2)
break;
assert(path.back() == s && path.front() == t);
// 增广路径,更新余留网的权值
augment_(path, minFlow_(path));
}
}
};
// 预流-压入最大流算法
// 【预流(preflow)】流网络中满足以下条件的正边流的集合,即各条边上的流小于等于该边容量,
// 而且对于每个内部顶点,流入量大于等于流出量。
// 【活动顶点(active vertex)】流入量大于流出量的内部顶点(约定源点和汇点是不活动的)。
// 【超额量(excess flow)】活动顶点的流入量与流出量之差。
// 【顶点高度】每个顶点被赋予一个高度值,其中:汇点h(t) = 0,余留网中的每条边u-v均有h(u) <= h(v) + 1。
// 【合格边】余留网中满足h(u) = h(v) + 1的一条边u-v。
// 算法框架如下(基于边):
// -- 初始化:从任意高度函数开始,并且除了连接到源点的边充满至其容量外,所有其他边为0流。
// -- 循环以下步骤,直至没有活动顶点为止:
// 1. 选择一个活动顶点;
// 2. 对离开该顶点的合格边(如果有的话)压入流;
// 3. 如果没有合格边,则增加顶点的高度。
// 算法时间复杂度为O(V^2*E)
// 以上算法并没有指定高度函数是什么、如何选择活动顶点、如何选择合格边、每次压入多少流等等,
// 通过对以上选项的不同选择,可得到不同的算法实现。
// 基于顶点的算法选择:
// 1. 选择一个活动顶点后,持续选择它的合格边,直至该顶点变为非活动或再无合格边为止。
// 2. 每次尽可能压入多的流量。
// KtMaxFlowPre是一个基于顶点算法的实现,并进一步具体化选项:
// 1. 使用FIFO队列依序选择活动顶点。
// 2. 源点高度初始化为V,其他为0。
// TODO: 1. 使用基于高度值的优先队列代替FIFO队列,能获得更好性能。
// 2. 更泛化的代码实现。
template<typename GRAPH, class WEIGHTOR = default_wtor<GRAPH>>
class KtMaxFlowPre : public KtMaxFlow<GRAPH, WEIGHTOR>
{
public:
using super_ = KtMaxFlow<GRAPH, WEIGHTOR>;
using super_::rg_;
using super_::addFlow_;
using super_::netflow;
using typename super_::flow_type;
KtMaxFlowPre(const GRAPH& g, unsigned s, unsigned t) : super_(g, s, t) {
// 各顶点的高度
std::vector<unsigned> height(g.order(), 0);
height[s] = g.order();
// 各顶点的超额量
// 源点的超额量初始化为足够大,以便在第一次循环时尽最大流量压入合格边。
std::vector<flow_type> excessFlow(g.order(), 0);
excessFlow[s] = std::numeric_limits<flow_type>::max();
// 活动顶点集,初始化为源点
std::queue<unsigned> activeVert;
activeVert.push(s);
// 预流-压入算法主循环
while (!activeVert.empty()) {
unsigned v = activeVert.front(); activeVert.pop();
if (excessFlow[v] == 0)
continue;
auto iter = KtAdjIter(rg_, v);
// 由于addFlow_会动态删增边,这将破坏迭代器数据,所以先统一收集邻接点
std::vector<std::pair<unsigned, flow_type>> adjs;
for (; !iter.isEnd(); ++iter)
adjs.emplace_back(*iter, iter.edge());
for(const auto& i : adjs) {
unsigned w = i.first;
auto pushFlow = std::min(i.second, excessFlow[v]);
// 对合格边进行流压入操作
if (pushFlow > 0 && (v == s || height[v] == height[w] + 1)) {
addFlow_(v, w, pushFlow);
excessFlow[v] -= pushFlow, excessFlow[w] += pushFlow;
if (w != s && w != t) {
assert(netflow(w) == excessFlow[w]);
activeVert.push(w);
}
}
}
// 如果v仍有超额量(必定没有合格边),增加v的高度,并重新将v加到活动顶点集
if (v != s && v != t && excessFlow[v] > 0) {
assert(netflow(v) == excessFlow[v]);
height[v]++;
activeVert.push(v);
}
}
}
};
|
koala999cn/kGraph
|
src/core/KtStronglyConnected.h
|
<filename>src/core/KtStronglyConnected.h<gh_stars>0
#pragma once
#include <vector>
#include "KtDfsIterX.h"
#include "KtTopologySort.h"
#include "../util/inverse.h"
/*
对于一个有向图顶点的子集S,如果在S内任取两个顶点u和v,都能找到一条从u到v的路径,那么S是强连通的。
如果在强连通的顶点集合S中加入其他任意顶点,它都不再是强连通的,那么S是原图的一个强连通分量(SCC:Strongly Connected Component)。
任意有向图都可以分解成若干不相干的SCC,这就是强连通分量分解。
把分解后的SCC缩成一个顶点,就得到一个DAG。
*/
class KvStronglyConnected
{
public:
// 返回强连通分量数目
unsigned count() const {
return numScc_;
}
// 判断节点v和w是否属于同一强连通分量
bool reachable(unsigned v, unsigned w) const {
return idScc_[v] == idScc_[w];
}
// 返回节点v所在强连通分量的ID
unsigned operator[](unsigned v) const {
return idScc_[v];
}
protected:
unsigned numScc_; // 强连通分量数目
std::vector<unsigned> idScc_; // 强连通分量的id,相同id的顶点属于同一强连通分量
};
// 基于Kosaraju算法的SCC分解
// 算法通过两遍简单的DFS实现:
// 第一遍:对所有顶点进行后序编号。完成后,越接近图的尾部(搜索树的叶子),顶点的编号越小。
// 第二遍:先将所有边反向(或进行逆图操作),然后以编号最大的顶点为起点进行DFS,遍历顶点集合即为一个SCC。
// 之后,只要还有尚未访问的顶点,就从中选取编号最大的不断重复DFS。
template<typename GRAPH>
class KtStronglyConnectedKos : public KvStronglyConnected
{
static_assert(GRAPH::isDigraph(), "KtStronglyConnectedKos must instantiated with DiGraph.");
public:
KtStronglyConnectedKos(const GRAPH& g) {
// 第一遍DFS
KtTopologySortInv<GRAPH> ts(g); // 拓扑排序算法只对DAG有效,所以此处使用基于DFS的逆拓扑排序计算后序编号
// 第二遍DFS
auto gR = inverse(g);
unsigned V = g.order();
numScc_ = 0;
idScc_.assign(V, -1);
unsigned i(V-1);
KtDfsIter<const GRAPH> iter(gR, -1);
while(true) {
iter.start(ts[i]);
while(!iter.isEnd()) {
if(iter.isTree()) {
assert(idScc_[*iter] == -1);
idScc_[*iter] = numScc_;
}
++iter;
}
++numScc_;
// 搜索尚未访问的最大编号顶点
while(i != 0 && idScc_[ts[--i]] != -1);
if(idScc_[ts[i]] != -1) // 所有顶点均已访问
break;
}
}
};
// 基于Tarjan算法的SCC分解
// 与findBridge算法相似,通过low值回溯以聚合连通分量
template<typename GRAPH>
class KtStronglyConnectedTar : public KvStronglyConnected
{
static_assert(GRAPH::isDigraph(), "KtStronglyConnectedTar must instantiated with DiGraph.");
public:
KtStronglyConnectedTar(const GRAPH& g) {
unsigned V = g.order();
numScc_ = 0;
idScc_.resize(V, -1);
std::vector<unsigned> S;
KtDfsIterX<const GRAPH, true> iter(g, 0);
while(!iter.isEnd()) {
unsigned v = *iter;
if(iter.isPushing())
S.push_back(v);
if(iter.isBridge()) {
unsigned w;
do {
w = S.back(); S.pop_back();
idScc_[w] = numScc_;
iter.resetLowIndex(w);
}while(w != v);
numScc_++;
}
++iter;
}
}
};
// 基于Gabow算法的SCC分解
template<typename GRAPH>
class KtStronglyConnectedGab : public KvStronglyConnected
{
static_assert(GRAPH::isDigraph(), "KtStronglyConnectedGab must instantiated with DiGraph.");
public:
KtStronglyConnectedGab(const GRAPH& g) {
unsigned V = g.order();
numScc_ = 0;
idScc_.resize(V, -1);
std::vector<unsigned> S, path;
KtDfsIter<const GRAPH, true, true, true> iter(g, 0);
while(!iter.isEnd()) {
unsigned v = *iter;
if(iter.isTree()) {
S.push_back(v);
path.push_back(v);
}
else if(idScc_[v] == -1) {
assert(iter.pushIndex(v) != -1);
while(iter.pushIndex(path.back()) > iter.pushIndex(v))
path.pop_back();
}
if(iter.isPopping() && path.back() == v) {
path.pop_back();
unsigned w;
do {
w = S.back(); S.pop_back();
idScc_[w] = numScc_;
}while(w != v);
numScc_++;
}
++iter;
}
}
};
|
koala999cn/kGraph
|
src/core/KtTopologySort.h
|
#pragma once
#include "KtDfsIter.h"
#include <assert.h>
#include <queue>
// 基于源点(入度为0的顶点)队列的拓扑排序算法
// 拓扑排序的2种定义:
// 1.重新编号:对DAG顶点重新编号从而使每条边由较小编号顶点指向较大编号顶点
// 2.重新整理:将DAG顶点在一条水平线上重新整理,从而使所有边均由左指向右
// 以上两种定义是等价和互逆的,若已知重新整理ts,则重新编号计算方法如下:tsI[ts[v]] = v
// 同样,若已知重新编号tsI,则重新整理计算方法如下:ts[tsI[v]] = v
template<typename DAG>
class KtTopologySort
{
static_assert(DAG::isDigraph(), "KtTopologySort must instantiated with Digraph.");
public:
KtTopologySort(const DAG& dag) {
//assert(!dag.hasLoop());
unsigned V = dag.order();
ts_.resize(V, -1); tsI_.resize(V, -1);
// 计算各顶点的入度
std::vector<unsigned> ins(V, 0);
for (unsigned v = 0; v < V; v++)
ins[v] = dag.indegree(v);
// 将源点推入队列q
std::queue<unsigned> q; // 源点队列
for(unsigned v = 0; v < V; v++)
if(ins[v] == 0) q.push(v);
assert(!q.empty());
// 按照FIFO顺序,对源点进行拓扑排序
for(unsigned i = 0; !q.empty(); i++) {
unsigned v = q.front(); q.pop();
ts_[i] = v;
tsI_[v] = i;
auto iter = KtAdjIter(dag, v);
for (; !iter.isEnd(); ++iter)
if(0 == --ins[*iter])
q.push(*iter);
}
}
// 返回重新整理
unsigned operator[](unsigned v) const {
return ts_[v];
}
// 返回重新编号
unsigned relabel(unsigned v) const {
return tsI_[v];
}
const auto& relabels() const {
return tsI_;
}
private:
std::vector<unsigned> ts_, tsI_;
};
// 基于Dfs算法的逆拓扑排序
// DFS中的后序编号可以得到一个逆拓扑排序
// 适用于非DAG
template<typename GRAPH>
class KtTopologySortInv
{
static_assert(GRAPH::isDigraph(), "KtTopologySortInv must instantiated with Digraph.");
public:
KtTopologySortInv(const GRAPH& g) : dfs_(g, 0) {
while(!dfs_.isEnd())
++dfs_;
unsigned V = g.order();
popI_.resize(V);
for (unsigned v = 0; v < V; v++) {
assert(relabel(v) < V);
popI_[relabel(v)] = v;
}
}
unsigned operator[](unsigned v) const {
return popI_[v];
}
unsigned relabel(unsigned v) const {
return dfs_.popIndex(v);
}
private:
KtDfsIter<const GRAPH, true> dfs_;
std::vector<unsigned> popI_;
};
|
koala999cn/kGraph
|
src/util/copy.h
|
<filename>src/util/copy.h<gh_stars>0
#pragma once
#include <assert.h>
#include "../core/KtWeightor.h"
template<typename SRC_G, typename DST_G,
typename WEIGHTOR = KtWeightSelf<typename SRC_G::edge_type>>
DST_G copy(const SRC_G& src)
{
DST_G dst;
dst.reserve(src.order(), src.size());
dst.reset(src.order());
for (unsigned v = 0; v < src.order(); v++) {
unsigned wMax = dst.isDigraph() ? unsigned(src.order()) : v + 1;
for (unsigned w = 0; w < wMax; w++)
for (auto r = src.edges(v, w); !r.empty(); ++r)
dst.addEdge(v, w, WEIGHTOR{}(*r));
if constexpr (SRC_G::hasVertex() && DST_G::hasVertex())
dst.vertexAt(v) = src.vertexAt(v);
}
return dst;
}
template<typename SRC_G, typename DST_G,
typename WEIGHTOR = KtWeightSelf<typename SRC_G::edge_type>>
void copy(const SRC_G& src, DST_G& dst)
{
dst = copy<SRC_G, DST_G, WEIGHTOR>(src);
}
|
koala999cn/kGraph
|
src/core/KtBipartite.h
|
<filename>src/core/KtBipartite.h<gh_stars>0
#pragma once
#include <assert.h>
#include "KtDfsIter.h"
// 二分图判定
// 若返回true,表示THIS是二分图,res元素值为1或者2,分别代表对应节点在不同分图
// 若返回false,表示THIS非二分图,res值等于-1的元素为冲突顶点
template<typename GRAPH>
class KtBipartite
{
static_assert(!GRAPH::isDigraph(), "KtBipartite cannot instantiated with Digraph.");
public:
// 采取2-着色法实现,通过DFS算法,不断对邻节点进行反着色,若无冲突则判定成功。
KtBipartite(const GRAPH& g) : color_(g.order(), 0), bipartite_(true) {
int color = 1;
KtDfsIter<const GRAPH, true, true> iter(g, 0);
color_[0] = color;
for (; !iter.isEnd(); ++iter) {
unsigned from = iter.from();
assert(from != -1 && color_[from] > 0);
color = 3 - color_[from]; // flip 1 & 2,着与父节点不同的颜色
unsigned v = *iter;
if (color_[v] == 3 - color) { // 着色冲突
color_[v] = -1;
bipartite_ = false;
break;
}
color_[v] = color; // 着色
}
}
// 是否二分图
bool ok() const { return bipartite_; }
// 返回顶点v的着色,值为1或者2,分别代表对应节点在不同分图,-1代表冲突点
int color(unsigned v) const { return color_[v]; }
private:
std::vector<int> color_;
bool bipartite_;
};
|
koala999cn/kGraph
|
src/core/KtGraph.h
|
<gh_stars>0
#pragma once
#include <algorithm>
#include <set>
#include "graph_traits.h"
#include "vertex_traits.h"
#include "edge_traits.h"
#include "../base/KtCondRange.h"
#include "KtAdjIter.h"
namespace kPrivate
{
template<bool reshapable, bool immutable>
struct graph_level {
constexpr static const int value = 0;
};
template<bool reshapable>
struct graph_level<reshapable, false> {
constexpr static const int value = 1;
};
template<>
struct graph_level<true, false> {
constexpr static const int value = 2;
};
template<typename GRAPH>
constexpr static const int graph_level_v =
graph_level<graph_traits<GRAPH>::reshapable, graph_traits<GRAPH>::immutable>::value;
template<typename EDGE_TYPE>
struct KpEdgeCompAllInOne {
bool operator()(unsigned to, const EDGE_TYPE& e) const {
return to < edge_traits<EDGE_TYPE>::to(e);
}
bool operator()(const EDGE_TYPE& e, unsigned to) const {
return edge_traits<EDGE_TYPE>::to(e) < to;
}
bool operator()(const EDGE_TYPE& e1, const EDGE_TYPE& e2) const {
return edge_traits<EDGE_TYPE>::to(e1) < edge_traits<EDGE_TYPE>::to(e2);
}
};
};
template<typename GRAPH_IMPL, bool digraph, bool multiEdges = false, bool alwaysSorted = false,
int level = kPrivate::graph_level_v<GRAPH_IMPL>>
class KtGraph : public GRAPH_IMPL
{
public:
using super_ = GRAPH_IMPL;
// 导入类型
using vertex_type = typename super_::vertex_type;
using edge_type = typename super_::edge_type;
using underly_vertex_t = typename graph_traits<GRAPH_IMPL>::underly_vertex_t;
using underly_edge_t = typename graph_traits<GRAPH_IMPL>::underly_edge_t;
using vertex_index_t = unsigned;
// 导入函数
using super_::super_;
using super_::order;
using super_::size;
using super_::outedges;
constexpr static bool isDigraph() { return digraph; }
constexpr static bool isDense() { return graph_traits<GRAPH_IMPL>::is_dense; }
constexpr static bool isMultiEdges() { return multiEdges && !isDense(); }
constexpr static bool isAlwaysSorted() { return alwaysSorted; }
constexpr static bool hasVertex() { return !std::is_void_v<vertex_type>; }
// 空图
bool isEmpty() const { return order() == 0; }
// 平凡图
bool isTrivial() const { return order() == 1; }
// 零图
bool isNull() const { return size() == 0; }
// 顶点v的出度,即v有多少条出边
unsigned outdegree(unsigned v) const {
if constexpr (vertexHasOutDegree_()) {
return outdegree_(v);
}
else if constexpr (!isDense()) {
return static_cast<unsigned>(outedges(v).size());
}
else {
struct {
bool operator()(const edge_type& e) {
return super_::null_edge != e;
}
} pred;
decltype(auto) r = outedges(v);
return static_cast<unsigned>(std::count_if(r.begin(), r.end(), pred));
}
}
// 入度
unsigned indegree(unsigned v) const {
if constexpr (!isDigraph()) {
return outdegree(v);
}
else {
unsigned d(0);
for (unsigned u = 0; u < order(); u++)
d += static_cast<unsigned>(edges(u, v).size());
return d;
}
}
// 度. 注:对于有向图的自环,度为2,1个入度+1个出度
unsigned degree(unsigned v) const {
auto d = outdegree(v);
if constexpr (isDigraph())
d += indegree(v);
return d;
}
auto edges(unsigned from, unsigned to) const {
decltype(auto) r = super_::outedges(from);
if constexpr (isDense()) {
auto first = std::next(r.begin(), to);
if (*first == super_::null_edge)
return KtRange(first, 0);
else
return KtRange(first, 1);
}
else if constexpr (isAlwaysSorted()) {
auto range = std::equal_range(r.begin(), r.end(), to,
kPrivate::KpEdgeCompAllInOne<underly_edge_t>{});
return KtRange(range.first, range.second);
}
else { // 需要进行全遍历,收集<from, to>的所有multi-edges
static_assert(has_to_v<underly_edge_t>, "edge missing property of 'to'");
auto pred = [to](typename decltype(r)::const_element_type e) {
return to == edge_traits<underly_edge_t>::to(e);
};
auto pos = std::find_if(r.begin(), r.end(), pred);
if constexpr (!isMultiEdges()) {
return KtRange(pos, pos == r.end() ? 0 : 1);
}
else {
return KtCondRange<decltype(pos), decltype(pred)>{ pos, r.end(), pred };
}
}
}
bool hasEdge(unsigned from, unsigned to) const {
return !edges(from, to).empty();
}
// 对多边图,返回第一条边
const edge_type& getEdge(unsigned from, unsigned to) const {
assert(hasEdge(from, to));
auto edges = this->edges(from, to);
return *edges;
}
// 仅对多边图有效
template<bool dummy = multiEdges, typename = std::enable_if_t<dummy>>
auto getEdge(unsigned from, unsigned to, const edge_type& edge) const {
auto edges = this->edges(from, to);
while (!edges.empty()) {
const edge_type& this_e = *edges;
if (this_e == edge)
return edges.begin();
++edges;
}
return edges.end();
}
// 仅对多边图有效
template<bool dummy = multiEdges, typename = std::enable_if_t<dummy>>
bool hasEdge(unsigned from, unsigned to, const edge_type& edge) const {
return getEdge(from, to, edge) != edges(from, to).end();
}
protected:
constexpr static bool vertexHasOutDegree_() {
return has_outdegree_v<underly_vertex_t>;
}
template<typename VERTEX_TYPE = underly_vertex_t,
std::enable_if_t<has_outdegree_v<VERTEX_TYPE>, bool> = true>
auto outdegree_(unsigned v) const {
return vertex_traits<VERTEX_TYPE>::outdegree(super_::vertexAt(v));
}
};
/////////////////////////////////////////////////////////////////////////////////////
/// 特化immutable接口:对应于level = 1
template<typename GRAPH_IMPL, bool digraph, bool multiEdges, bool alwaysSorted>
class KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 1>
: public KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 0>
{
public:
using super_ = KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 0>;
using typename super_::edge_type;
using typename super_::underly_edge_t;
using super_::edges; // 导入const版本的edges
using super_::isDigraph;
using super_::isDense;
using super_::isAlwaysSorted;
using super_::isMultiEdges;
// 提供一个可写版本的edges实现
auto edges(unsigned from, unsigned to) {
decltype(auto) r = super_::outedges(from);
if constexpr (isDense()) {
auto first = std::next(r.begin(), to);
if (*first == super_::null_edge)
return KtRange(first, 0);
else
return KtRange(first, 1);
}
else if constexpr (isAlwaysSorted()) {
auto range = std::equal_range(r.begin(), r.end(), to,
kPrivate::KpEdgeCompAllInOne<underly_edge_t>{});
return KtRange(range.first, range.second);
}
else {
auto pred = [to](typename decltype(r)::const_element_type e) {
return to == edge_traits<underly_edge_t>::to(e);
};
auto pos = std::find_if(r.begin(), r.end(), pred);
if constexpr (!isMultiEdges()) {
return KtRange(pos, pos == r.end() ? 0 : 1);
}
else {
return KtCondRange<decltype(pos), decltype(pred)>{ pos, r.end(), pred };
}
}
}
// 仅对多边图有效
template<bool dummy = !multiEdges, typename = std::enable_if_t<dummy>>
void setEdge(unsigned from, unsigned to, const edge_type& edge) {
assert(super_::hasEdge(from, to));
auto edges = this->edges(from, to);
assert(edges.size() == 1);
*edges = edge;
if constexpr (!isDigraph())
*this->edges(to, from) = edge;
}
// 仅对多边图有效
template<bool dummy = multiEdges, typename = std::enable_if_t<dummy>>
void setEdge(unsigned from, unsigned to, const edge_type& curEdge, const edge_type& newEdge) {
assert(super_::hasEdge(from, to, curEdge));
decltype(auto) iter = getEdge_(from, to, curEdge);
*iter = newEdge;
if constexpr (!isDigraph())
if (from != to) {
assert(super_::hasEdge(to, from, curEdge));
decltype(auto) iter = getEdge_(to, from, curEdge);
*iter = newEdge;
}
}
using super_::getEdge;
// 对于有向单边图提供getEdge的左值接口,无向图则不行
// 因为无向图实际上保存着两条边,需要保持权值一致性
template<bool dummy = !multiEdges && digraph, typename = std::enable_if_t<dummy>>
edge_type& getEdge(unsigned from, unsigned to) {
auto edges = this->edges(from, to);
assert(edges.size() == 1);
return *edges;
}
protected:
// 仅对多边图有效
template<bool dummy = multiEdges, typename = std::enable_if_t<dummy>>
auto getEdge_(unsigned from, unsigned to, const edge_type& edge) {
auto edges = this->edges(from, to);
while (!edges.empty()) {
const edge_type& this_e = *edges;
if (this_e == edge)
return edges.begin();
++edges;
}
return edges.end();
}
};
/////////////////////////////////////////////////////////////////////////////////////
/// 特化reshapable接口:对应于level = 2
//
template<typename GRAPH_IMPL, bool digraph, bool multiEdges, bool alwaysSorted>
class KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 2>
: public KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 1>
{
public:
using super_ = KtGraph<GRAPH_IMPL, digraph, multiEdges, alwaysSorted, 1>;
using typename super_::edge_type;
using underly_vertex_t = typename graph_traits<super_>::underly_vertex_t;
using underly_edge_t = typename graph_traits<super_>::underly_edge_t;
using edge_iter = typename graph_traits<super_>::edge_iter;
using const_edge_iter = typename graph_traits<super_>::const_edge_iter;
using super_::isDigraph;
using super_::isDense;
using super_::isAlwaysSorted;
using super_::isMultiEdges;
using super_::reset;
using super_::order;
KtGraph() = default;
KtGraph(unsigned nv) {
reset(nv);
}
// addVertex直接使用基类的实现
using super_::addVertex;
void addEdge(unsigned from, unsigned to, const edge_type& edge) {
addEdge_(from, to, edge);
if constexpr (!isDigraph()) {
if (from != to)
addEdge_<true>(to, from, edge);
}
}
// 若edge具to属性,提供一个简化版的addEdge接口
template<typename EDGE_TYPE,
std::enable_if_t<has_to_v<EDGE_TYPE>, bool> = true>
void addEdge(unsigned from, const EDGE_TYPE& edge) {
addEdge(from, edge_traits<EDGE_TYPE>::to(edge), edge);
}
// 若允许(edge_type可整型构造),则提供一个addEdge的简化版
template<typename EDGE_TYPE = edge_type,
std::enable_if_t<std::is_constructible_v<EDGE_TYPE, int>, bool> = true>
void addEdge(unsigned from, unsigned to) {
addEdge(from, to, EDGE_TYPE{ 1 });
}
using super_::eraseEdge; // 导出基类的eraseEdge,KtAdjIter要用到
// 删除from到to的所有边
void eraseEdge(unsigned from, unsigned to) {
eraseEdge_(from, to);
if constexpr (!isDigraph()) {
if (from != to)
eraseEdge_<true>(to, from);
}
}
// 仅对多边图有效
template<bool dummy = multiEdges, typename = std::enable_if_t<dummy>>
void eraseEdge(unsigned v, unsigned w, const edge_type& val) {
assert(super_::hasEdge(v, w, val));
auto pos = super_::getEdge_(v, w, val);
super_::eraseEdge(v, pos);
if constexpr (super_::vertexHasOutDegree_())
outdegree_(v)--;
if constexpr (!isDigraph())
if (v != w) {
super_::template eraseEdge<true>(w, super_::getEdge_(w, v, val));
if constexpr (super_::vertexHasOutDegree_())
outdegree_(w)--;
}
}
// TODO: 优化
void eraseOutEdges(unsigned v) {
if constexpr (isDense()) {
for (unsigned u = 0; u < order(); u++)
eraseEdgeIfExist_(v, u);
}
else {
decltype(auto) r = super_::outedges(v);
std::set<unsigned> us; // 兼容类似flat图的边存储布局,先保存各条边的to顶点,而后再删除无向图(to, from)边
// 如果先执行删除操作,可能会影响已在r中的迭代器
// 考虑多边,选择set容器
if constexpr (!isDigraph())
for (auto& e : r)
us.insert(to_(e));
if constexpr (super_::vertexHasOutDegree_())
outdegree_(v) -= r.size();
super_::eraseEdges(v, r.begin(), r.end());
if constexpr (!isDigraph())
for(auto u : us)
if(u != v)
eraseEdge_<true>(u, v);
}
}
void eraseInEdges(unsigned v) {
if constexpr (!isDigraph()) {
eraseOutEdges(v);
}
else {
for (unsigned u = 0; u < order(); u++)
eraseEdgeIfExist_(u, v);
}
}
// 删除与顶点v相接的所有边
void eraseEdges(unsigned v) {
eraseOutEdges(v);
if constexpr (isDigraph())
eraseInEdges(v);
}
void eraseVertex(unsigned v) {
eraseEdges(v);
super_::eraseVertex(v);
// 调整各边的to值
// TODO: 考虑alwaysSorted优化
if constexpr (!isDense()) {
for (unsigned i = 0; i < order(); i++) {
decltype(auto) r = super_::outedges(i);
for (auto& e : r) {
assert(to_(e) != v);
if (to_(e) > v) to_(e)--;
}
}
}
}
private:
// @dummy: 若为true,则表示添加的是无向图边的反向边
template<bool dummy = false>
void addEdge_(unsigned from, unsigned to, const edge_type& edge) {
decltype(auto) r = super_::outedges(from);
if constexpr (isDense()) {
super_::template addEdge<dummy>(from, std::next(r.begin(), to), edge);
}
else if constexpr (!isAlwaysSorted()) {
static_assert(has_to_v<underly_edge_t>, "edge missing property of 'to'");
auto iter = super_::template addEdge<dummy>(from, r.end(), edge); // 若不排序,添加边到尾部
to_(*iter) = to;
}
else {
auto pos = std::lower_bound(r.begin(), r.end(), to,
kPrivate::KpEdgeCompAllInOne<underly_edge_t>{});
auto iter = super_::template addEdge<dummy>(from, pos, edge);
to_(*iter) = to;
}
if constexpr (super_::vertexHasOutDegree_())
outdegree_(from)++;
}
template<bool dummy = false>
void eraseEdge_(unsigned from, unsigned to) {
auto edges = super_::edges(from, to);
assert(edges.size() > 0);
if constexpr (!isMultiEdges()) {
assert(edges.size() == 1);
super_::template eraseEdge<dummy>(from, edges.begin());
if constexpr (super_::vertexHasOutDegree_())
outdegree_(from)--;
}
else if constexpr (isAlwaysSorted()) {
super_::template eraseEdges<dummy>(from, edges.begin(), edges.end());
if constexpr (super_::vertexHasOutDegree_())
outdegree_(from) -= edges.size();
}
else {// 未排序的多边,依次检查
do {
auto pos = super_::template eraseEdge<dummy>(from, edges.begin());
auto end = super_::outedges(from).end();
edges.reset(pos, end);
if constexpr (super_::vertexHasOutDegree_())
outdegree_(from)--;
edges.meetCond_();
} while (!edges.empty());
}
}
void eraseEdgeIfExist_(unsigned from, unsigned to) {
if (!super_::edges(from, to).empty()) {
eraseEdge_(from, to);
if constexpr (!isDigraph())
if(from != to )
eraseEdge_<true>(to, from);
}
}
template<typename EDGE_TYPE,
std::enable_if_t<has_to_v<EDGE_TYPE>
&& !std::is_const_v<EDGE_TYPE>, bool> = true>
static decltype(auto) to_(const EDGE_TYPE& e) {
return edge_traits<EDGE_TYPE>::to(e);
}
template<typename EDGE_TYPE,
std::enable_if_t<has_to_v<EDGE_TYPE>, bool> = true>
static decltype(auto) to_(EDGE_TYPE& e) {
return edge_traits<EDGE_TYPE>::to(e);
}
template<typename VERTEX_TYPE = underly_vertex_t,
std::enable_if_t<has_outdegree_v<VERTEX_TYPE>, bool> = true>
decltype(auto) outdegree_(unsigned v) {
return vertex_traits<VERTEX_TYPE>::outdegree(super_::vertexAt(v));
}
};
|
willyu-elastic/SimpleEndpoint
|
SimpleEndpointApp/SimpleEndpointApp/SystemRequestDelegate.h
|
#pragma once
#import <Availability.h>
#import <NetworkExtension/NetworkExtension.h>
#import <SystemExtensions/SystemExtensions.h>
@interface SystemExtensionLoadRequestDelegate : NSObject<OSSystemExtensionRequestDelegate>
///
/// @brief This static method will pull the bundle instance of our system extension
/// from a set relative path inside our .app
///
+ (NSBundle *)extensionBundle;
@property BOOL successfulExtensionLoad;
@property dispatch_semaphore_t sema;
@end
@interface SystemExtensionUnloadRequestDelegate : NSObject<OSSystemExtensionRequestDelegate>
@property BOOL successfulExtensionUnload;
@property dispatch_semaphore_t sema;
@end
|
willyu-elastic/SimpleEndpoint
|
SharedIPC/SharedIPC.h
|
<reponame>willyu-elastic/SimpleEndpoint<gh_stars>10-100
#pragma once
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger,
NetworkEventDataTypes) {
NetworkEventDataTypesNone = 0,
RemoteAddress = 1,
LocalAddress = 2,
LocalPort = 3,
RemotePort = 4,
NetworkEventType = 5,
NetworkDirection = 6,
NetworkProtocol = 7,
};
///
/// @brief This protocol is implemented by the receiving process to be called
/// by the System Extension to notify the receving process of a new
/// network event that has occured
///
@protocol DaemonCommunication<NSObject>
- (void)notifyNetworkEventWithDictionary:(NSDictionary<NSNumber *,
NSObject *> *_Nonnull)data
withCompletionHandler:(void (^_Nonnull)(bool success))reply;
@end
///
/// @brief This protocol is implemented by the receiving process to be called
/// by the System Extension to notify the receving process of a new
/// network event that has occured
///
@protocol ProviderCommunication<NSObject>
- (void)registerWithCompletionHandler:(void (^_Nonnull)(bool success))completionHandler;
@end
///
/// @brief This is an Objective C class that is used by both the receiving application
/// and the System Extension to communicate with each other
///
@interface IPCConnection : NSObject<NSXPCListenerDelegate, ProviderCommunication>
// Used only by the System Extension side of IPC. Need to
// keep a reference to listener to prevent ARC from cleaning it up after
// we initialize a new listener
@property(nonatomic, retain) NSXPCListener *_Nonnull listener;
// The underlying connection between the System Extension and the receiving process
@property(nonatomic, retain) NSXPCConnection *_Nullable currentConnection;
// This is set to the delegate that is passed in during IPC registration
@property(nonatomic, weak) NSObject<DaemonCommunication> *_Nullable delegate;
///
/// @brief This method will return a shared static instance for IPCing back and forth between
/// the System Extension and the receiving application
///
/// @returns A static shared instance (singleton) to IPCConnection object
///
+ (IPCConnection *_Nonnull)shared;
///
/// @brief This method is called by the receiving application to intiate a connection with
/// the System Extension
///
/// @param[in] bundle This is the bundle to connect with, in this case the bundle is the System
/// Extension
///
/// @param[in] delegate This parameter is an instance of an object that implements the
/// AppCommunication
/// protocol and is the exported interface used to communicate with the
/// receiving application
///
/// @param[in] completionHandler This is a callback passed in that is called by this method once
/// registration has
/// finished successfully or has failed
///
- (void)registerWithBundle:(NSBundle *_Nonnull)bundle
withDelegate:(NSObject<DaemonCommunication> *_Nonnull)delegate
withCompletionHandler:(void (^_Nonnull)(bool success))completionHandler;
///
/// @brief This method is called by the System Extension to send over information regarding an new
/// network event
///
/// @param[in] data This is an NSDictionary that contains information about the network event
/// such as IP address, port, and any possible DNS queries
///
/// @param[in] responseHandler This is a callback that is passed to the receiving application to
/// call once it has successfully
/// received the data
///
- (void)notifyListenerAboutNetworkEventWithDictionary:(NSDictionary<NSNumber *,
NSObject *> *_Nonnull)data
withResponseHandler:
(void (^_Nonnull)(bool success))responseHandler;
///
/// @brief This method is part of the protocol defined by NSXPCListenerDelegate which this
/// class implements. It is called by the XPC subsystem to determine if the new connection
/// should be accepted or not
///
/// @param[in] newConnection The new connection to save and interact with if it is accepted
///
- (BOOL)listener:(NSXPCListener *_Nonnull)listener
shouldAcceptNewConnection:(NSXPCConnection *_Nonnull)newConnection;
///
/// @brief This method is called by the System Extension to begin listening for new connections
/// from the receiving application
///
- (void)startListener;
///
/// @brief This method is part of the protocol ProviderCommunication and called by the receiving
/// application to register with the System Extension
///
/// @param[in] completionHandler A callback that is called by the System Extension to notify the
/// receiving application that registration was successful
///
- (void)registerWithCompletionHandler:(void (^_Nonnull)(bool success))completionHandler;
@end
|
willyu-elastic/SimpleEndpoint
|
launchDaemon/launchDaemon/ESHooks.h
|
<gh_stars>10-100
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
bool InstallHooks(void);
bool UninstallHooks(void);
#ifdef __cplusplus
}
#endif
|
willyu-elastic/SimpleEndpoint
|
SimpleEndpointApp/SimpleEndpointExtension/FilterDataProvider.h
|
//
// FilterPacketProvider.h
// SimpleEndpointExtension
//
// Created by will on 2/5/20.
// Copyright © 2020 YourCompanyHere. All rights reserved.
//
#import <NetworkExtension/NetworkExtension.h>
@interface FilterDataProvider : NEFilterDataProvider
@end
|
TfEL/sturdy-dollop
|
TextMutationTests/ViewController.h
|
//
// ViewController.h
// TextMutationTests
//
// Created by <NAME> on 24/07/2015.
// Copyright (c) 2015 Department for Education and Child Development. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextView *textView;
@end
|
TfEL/sturdy-dollop
|
TextMutationTests/settingsTableViewController.h
|
//
// settingsTableViewController.h
// TextMutationTests
//
// Created by <NAME> on 24/07/2015.
// Copyright (c) 2015 Department for Education and Child Development. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface settingsTableViewController : UITableViewController
@property (weak, nonatomic) IBOutlet UITextField *stringValue;
@property (weak, nonatomic) IBOutlet UITextField *htmlValue;
- (IBAction)saveButton:(id)sender;
@end
|
TfEL/sturdy-dollop
|
TextMutationTests/webViewController.h
|
<gh_stars>0
//
// webViewController.h
// TextMutationTests
//
// Created by <NAME> on 24/07/2015.
// Copyright (c) 2015 Department for Education and Child Development. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface webViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
|
bswags/web3swift
|
Sources/libscrypt/libscrypt.c
|
<gh_stars>0
//
// libscrypt.c
// libscrypt
//
// Created by <NAME> on 11/10/21.
// Copyright © 2021 web3swift. All rights reserved.
//
#include "b64.h"
#include "crypto_scrypt-hexconvert.h"
#include "libscrypt.h"
|
haobinnan/CrystalDiskInfo
|
FontSelectionDlg.h
|
/*---------------------------------------------------------------------------*/
// Author : hiyohiyo
// Mail : <EMAIL>
// Web : https://crystalmark.info/
// License : The MIT License
/*---------------------------------------------------------------------------*/
#pragma once
#include "afxwin.h"
#include "ButtonFx.h"
#include "ComboBoxFx.h"
#include "FontComboBoxFx.h"
class CFontSelectionDlg : public CDialogFx
{
DECLARE_DYNAMIC(CFontSelectionDlg)
static const int SIZE_X = 480;
static const int SIZE_Y = 208;
enum { IDD = IDD_FONT };
public:
CFontSelectionDlg(CWnd* pParent = NULL);
virtual ~CFontSelectionDlg();
CString GetFontFace();
int GetFontScale();
protected:
virtual void DoDataExchange(CDataExchange* pDX);
virtual BOOL OnInitDialog();
virtual void UpdateDialogSize();
void SetDefaultFont(CString fontFace);
DECLARE_MESSAGE_MAP()
afx_msg void OnSetDefault();
afx_msg void OnOk();
CStaticFx m_LabelFontFace;
CStaticFx m_LabelFontScale;
CButtonFx m_CtrlOk;
CButtonFx m_CtrlSetDefault;
CFontComboBox m_CtrlFontFace;
CComboBoxFx m_CtrlFontScale;
};
|
haobinnan/CrystalDiskInfo
|
Priscilla/ListCtrlFx.h
|
/*---------------------------------------------------------------------------*/
// Author : hiyohiyo
// Mail : <EMAIL>
// Web : https://crystalmark.info/
// License : The MIT License
/*---------------------------------------------------------------------------*/
#pragma once
#include "CommonFx.h"
#include "HeaderCtrlFx.h"
#include <atlimage.h>
#include <gdiplus.h>
#pragma comment(lib, "Gdiplus.lib")
using namespace Gdiplus;
class CListCtrlFx : public CListCtrl
{
DECLARE_DYNAMIC(CListCtrlFx)
public:
CListCtrlFx();
virtual ~CListCtrlFx();
void SetTextColor1(COLORREF color);
void SetTextColor2(COLORREF color);
void SetTextSelected(COLORREF color);
void SetBkColor1(COLORREF color);
void SetBkColor2(COLORREF color);
void SetBkSelected(COLORREF color);
void SetLineColor1(COLORREF color);
void SetLineColor2(COLORREF color);
void SetGlassColor(COLORREF glassColor, BYTE glassAlpha);
COLORREF GetTextColor1();
COLORREF GetTextColor2();
COLORREF GetTextSelected();
COLORREF GetBkColor1();
COLORREF GetBkColor2();
COLORREF GetBkSelected();
COLORREF GetLineColor1();
COLORREF GetLineColor2();
BOOL InitControl(int x, int y, int width, int height, int maxWidth, int maxHeight, double zoomRatio, CDC* bkDC, int renderMode, BOOL bHighContrast, BOOL bDarkMode);
void SetFontEx(CString face, int size, double zoomRatio, double fontRatio = 1.0);
void EnableHeaderOwnerDraw(BOOL bOwnerDraw);
protected:
virtual void PreSubclassWindow();
void SetupControlImage(CBitmap& bkBitmap, CBitmap& ctrlBitmap);
DECLARE_MESSAGE_MAP()
afx_msg void OnCustomdraw(NMHDR* pNMHDR, LRESULT* pResult);
int m_X;
int m_Y;
BOOL m_bNT6orLater;
CSize m_CtrlSize;
CRect m_Margin;
int m_RenderMode;
BOOL m_bHighContrast;
BOOL m_bDarkMode;
CHeaderCtrlFx m_Header;
COLORREF m_TextColor1;
COLORREF m_TextColor2;
COLORREF m_TextSelected;
COLORREF m_BkColor1;
COLORREF m_BkColor2;
COLORREF m_BkSelected;
COLORREF m_LineColor1;
COLORREF m_LineColor2;
CFont m_Font;
CImageList m_Image;
CDC* m_BkDC;
// Glass
COLORREF m_GlassColor;
BYTE m_GlassAlpha;
// Image
CBitmap m_BkBitmap;
CBitmap m_CtrlBitmap;
CImage m_CtrlImage;
};
|
haobinnan/CrystalDiskInfo
|
Priscilla/MainDialogFx.h
|
<filename>Priscilla/MainDialogFx.h
/*---------------------------------------------------------------------------*/
// Author : hiyohiyo
// Mail : <EMAIL>
// Web : https://crystalmark.info/
// License : The MIT License
/*---------------------------------------------------------------------------*/
#pragma once
#include "DialogFx.h"
#include "UtilityFx.h"
#include "OsInfoFx.h"
class CMainDialogFx : public CDialogFx
{
public:
CMainDialogFx(UINT dlgResouce, CWnd* pParent = NULL);
virtual ~CMainDialogFx();
// Zoom
DWORD GetZoomType();
void SetZoomType(DWORD zoomType);
// Getter
int GetFontScale();
double GetFontRatio();
CString GetFontFace();
CString GetCurrentLangPath();
CString GetDefaultLangPath();
CString GetThemeDir();
CString GetCurrentTheme();
CString GetDefaultTheme();
CString GetParentTheme1();
CString GetParentTheme2();
CString GetIniPath();
void SaveImage();
protected:
void InitMenu();
void InitThemeLang();
void ChangeTheme(CString ThemeName);
void SetWindowTitle(CString message);
void UpdateThemeInfo();
COLORREF GetControlColor(CString name, BYTE defaultColor, CString theme);
BYTE GetControlAlpha(CString name, BYTE defaultAlpha, CString theme);
BYTE GetCharacterPosition(CString theme);
CString GetParentTheme(int i, CString theme);
void SaveImageDlg(CImage* image);
virtual BOOL OnInitDialog();
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual BOOL CheckThemeEdition(CString name);
virtual CString GetDefaultFont();
DECLARE_MESSAGE_MAP()
afx_msg void OnWindowPosChanging(WINDOWPOS* lpwndpos);
// Common
BOOL m_bStartup;
BOOL m_bWindowMinimizeOnce;
BOOL m_bResident;
BOOL m_bResidentMinimize;
// Theme
CString m_ThemeKeyName;
CString m_RecommendTheme;
CStringArray m_MenuArrayTheme;
// Language
CStringArray m_MenuArrayLang;
#ifdef OPTION_TASK_TRAY
// Task Tray
static UINT wmTaskbarCreated;
BOOL AddTaskTray(UINT id, UINT callback, HICON icon, CString tip);
BOOL RemoveTaskTray(UINT id);
BOOL ModifyTaskTray(UINT id, HICON icon, CString tip);
BOOL ModifyTaskTrayIcon(UINT id, HICON icon);
BOOL ModifyTaskTrayTip(UINT id, CString tip);
BOOL ShowBalloon(UINT id, DWORD infoFlag, CString infoTitle, CString info);
#endif
};
|
cben-bar/42-pipex
|
srcs/ft_strnstr.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strnstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cben-bar <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/08 04:44:01 by cben-bar #+# #+# */
/* Updated: 2022/04/07 23:43:20 by cben-bar ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/pipex.h"
static int ft_search(const char *hsk, const char *ndl, size_t i, size_t len)
{
size_t i_n;
i_n = 0;
if (ndl[i_n] && i < len)
{
while (ndl[i_n] == hsk[i] && i < len)
{
if (ndl[i_n + 1] == '\0')
return (1);
i_n++;
i++;
}
}
return (0);
}
char *ft_strnstr(const char *haystack, const char *needle, size_t len)
{
size_t i;
i = 0;
if (!ft_strlen(needle))
return ((char *)haystack);
while (i < len && haystack[i] != 0)
{
if (ft_search(haystack, needle, i, len))
return ((char *)&haystack[i]);
i++;
}
return (0);
}
|
cben-bar/42-pipex
|
srcs/utils.c
|
<filename>srcs/utils.c<gh_stars>0
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cben-bar <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/07 23:31:37 by cben-bar #+# #+# */
/* Updated: 2022/04/19 17:18:38 by cben-bar ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/pipex.h"
char *get_path(char *cmd, char **envp, size_t j)
{
char **paths;
char *path;
char *part_path;
while (ft_strnstr(envp[j], "PATH", 4) == 0)
j++;
if (j > line_count(envp))
error(NULL);
paths = ft_split(envp[j] + 5, ':');
j = 0;
if (access(cmd, F_OK) == 0)
return (cmd);
while (paths[j])
{
part_path = ft_strjoin(paths[j], "/");
path = ft_strjoin(part_path, cmd);
free(part_path);
if (access(path, F_OK) == 0)
return (path);
free(path);
j++;
}
cleaner(paths);
return (0);
}
void error(const char *msg)
{
if (msg)
perror(msg);
else
perror("Error");
exit(EXIT_FAILURE);
}
void execute(char *av, char **envp)
{
char **cmd;
int i;
char *path;
size_t j;
i = -1;
j = 0;
cmd = ft_split(av, ' ');
path = get_path(cmd[0], envp, j);
if (!path)
{
while (cmd[++i])
free(cmd[i]);
free(cmd);
error("command not found");
}
if (execve(path, cmd, envp) == -1)
error("command not found");
}
|
cben-bar/42-pipex
|
includes/pipex.h
|
<reponame>cben-bar/42-pipex<gh_stars>0
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cben-bar <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/08 10:33:11 by cben-bar #+# #+# */
/* Updated: 2022/04/19 17:01:11 by cben-bar ### ########lyon.fr */
/* */
/* ************************************************************************** */
#ifndef PIPEX_H
# define PIPEX_H
/* ****************************************************************************
-----------------------------------INCLUDES-----------------------------------
* ************************************************************************** */
# include <stdlib.h>
# include <unistd.h>
# include <string.h>
# include <stdio.h>
# include <sys/wait.h>
# include <fcntl.h>
/* ****************************************************************************
-----------------------------PROTOTYPES FUNCTIONS-----------------------------
* ************************************************************************** */
void error(const char *msg);
size_t line_count(char **tab);
char *find_path(char *cmd, char **envp);
void execute(char *av, char **envp);
char **ft_split(char const *s, char c);
char *ft_strjoin(const char *s1, const char *s2);
size_t ft_strlen(const char *s);
char *ft_strnstr(const char *haystack, const char *needle, size_t len);
void ft_putstr_fd(char *s, int fd);
void ft_putchar_fd(char c, int fd);
void cleaner(char **tab);
#endif
|
cben-bar/42-pipex
|
srcs/ft_strjoin.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cben-bar <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/12 00:13:48 by cben-bar #+# #+# */
/* Updated: 2022/04/07 23:42:42 by cben-bar ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/pipex.h"
char *ft_strjoin(const char *s1, const char *s2)
{
char *joined;
size_t len;
size_t i;
size_t j;
i = -1;
j = -1;
if (!s1 || !s2)
return (NULL);
len = ft_strlen(s1) + ft_strlen(s2);
joined = malloc(sizeof(char) * (len + 1));
if (!joined)
return (NULL);
while (s1[++i])
joined[i] = s1[i];
while (s2[++j])
joined[i + j] = s2[j];
joined[len] = '\0';
return (joined);
}
|
cben-bar/42-pipex
|
srcs/pipex.c
|
<reponame>cben-bar/42-pipex
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cben-bar <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/07 23:30:43 by cben-bar #+# #+# */
/* Updated: 2022/04/19 16:11:50 by cben-bar ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/pipex.h"
void child(char **av, char **envp, int *fd)
{
int infile;
infile = open(av[1], O_RDONLY, 0777);
if (infile == -1)
error(NULL);
dup2(fd[1], STDOUT_FILENO);
dup2(infile, STDIN_FILENO);
close(fd[0]);
execute(av[2], envp);
}
void parent(char **av, char **envp, int *fd)
{
int outfile;
outfile = open(av[4], O_CREAT | O_WRONLY | O_TRUNC, 0777);
if (outfile == -1)
error(NULL);
dup2(fd[0], STDIN_FILENO);
dup2(outfile, STDOUT_FILENO);
execute(av[3], envp);
}
int main(int ac, char **av, char **envp)
{
int fd[2];
pid_t pid1;
pid_t pid_p;
if (ac == 5)
{
if (pipe(fd) == -1)
error(NULL);
pid1 = fork();
if (pid1 == -1)
error(NULL);
if (pid1 == 0)
child(av, envp, fd);
pid_p = fork();
close(fd[1]);
if (pid_p == 0)
parent(av, envp, fd);
waitpid(pid1, NULL, 0);
waitpid(pid_p, NULL, 0);
}
else
{
ft_putstr_fd("Error: Bad arguments\n", 2);
}
return (0);
}
|
kellsnc/sadx-limit-break
|
limit-break/clip.h
|
#pragma once
// Current clip distance - cannot exceed clip_current
extern float clip_current;
// Clip distance upper limit
extern float clip_limit;
// Minimum recorded clip distance above clip_default
extern float clip_min;
// Maximum recorded clip distance
extern float clip_max;
// Default SADX object clip distance
extern const float clip_default;
void clip_init();
// Reset current clip distance and limit to defaults
void clip_reset(float limit = 0.0f);
bool clip_increase(float inc);
bool clip_decrease(float dec);
|
kellsnc/sadx-limit-break
|
limit-break/stdafx.h
|
#pragma once
#include <SADXModLoader.h>
#include <Trampoline.h>
#include <vector>
#include <deque>
#include <cstdint>
#include "object.h"
#include "clip.h"
#include "collision.h"
#include "textures.h"
#include "set.h"
#include "objdef.h"
|
kellsnc/sadx-limit-break
|
limit-break/textures.h
|
#pragma once
void textures_init();
void textures_OnFrame();
|
kellsnc/sadx-limit-break
|
limit-break/misc.h
|
#pragma once
// from: https://github.com/nihilus/hexrays_tools/blob/master/code/defs.h
#define _LOBYTE(x) (*((Uint8*)&(x))) // low byte
#define BYTEn(x, n) (*((Uint8*)&(x)+n))
#define BYTE1(x) BYTEn(x, 1) // byte 1 (counting from 0)
|
kellsnc/sadx-limit-break
|
limit-break/set.h
|
<gh_stars>1-10
#pragma once
void set_init();
|
kellsnc/sadx-limit-break
|
limit-break/objdef.h
|
#pragma once
void objdef_init();
|
kellsnc/sadx-limit-break
|
limit-break/object.h
|
<filename>limit-break/object.h
#pragma once
void object_init();
void object_OnFrame();
|
kellsnc/sadx-limit-break
|
limit-break/collision.h
|
#pragma once
void collision_init();
|
Kashish410/Project-alpha
|
C/LeapYear.c
|
#include <stdio.h>
int main(void) {
int year;
scanf("%d", &year);
if(year % 4 == 0){
if(year % 100 != 0){
printf("Yes, %d is a leap year!", year);
}
else if(year % 400 != 0){
printf("No, %d is not a leap year!", year);
}
else{
printf("Yes, %d is a leap year!", year);
}
}
else{
printf("No, %d is not a leap year!", year);
}
return 0;
}
|
Kashish410/Project-alpha
|
transpose_of_matrix.c
|
<filename>transpose_of_matrix.c<gh_stars>0
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c, i, j;
scanf("%d %d", &r, &c);
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
scanf("%d", &a[i][j]);
}
// Finding the transpose of matrix a
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
for (i = 0; i < c; ++i)
for (j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
|
wotsen/util_phread
|
test.c
|
/**
* @file test.c
* @author 余王亮 (<EMAIL>)
* @brief
* @version 0.1
* @date 2019-11-02
*
* @copyright Copyright (c) 2019
*
*/
#include <unistd.h>
#include "util_pthread.h"
void *test(void *arg)
{
set_thread_name("test");
while (1)
{
printf("..................\n");
sleep(3);
}
}
int main(void)
{
pthread_t tid;
if (create_thread(&tid, PTHREAD_STACK_MIN, SYS_THREAD_PRI_LV, test, NULL))
{
printf("create %zu success\n", tid);
}
while (1);
return 0;
}
|
wotsen/util_phread
|
include/util_pthread.h
|
<reponame>wotsen/util_phread<gh_stars>0
/**
* @file util_pthread.h
* @author 余王亮 (<EMAIL>)
* @brief
* @version 0.1
* @date 2019-11-02
*
* @copyright Copyright (c) 2019
*
*/
#ifndef __UTIL_PTHREAD_H__
#define __UTIL_PTHREAD_H__
#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>
#define INVALID_PTHREAD_TID -1
///< 线程名最长长度
#define MAX_THREAD_NAME_LEN 15
///< 栈长度,传入数字以k为单位
#define STACKSIZE(k) ((k)*1024)
///< 最小栈
#ifndef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 16384
#endif
#define MAX_THREAD_PRI_LV 100
#define SYS_THREAD_PRI_LV 90
#define RUN_THREAD_PRI_LV 80
#define FUN_THREAD_PRI_LV 70
#define THR_THREAD_PRI_LV 60
#define MIN_THREAD_PRI_LV 50
///< 线程毁掉接口
typedef void *(*thread_func)(void *);
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
///< 创建线程
bool create_thread(pthread_t *tid, const size_t stacksize, const int priority, thread_func fn, void *arg);
///< 设置线程名
void set_thread_name(const char *name);
///< 释放线程
bool release_thread(const pthread_t tid);
///< 检测线程存活
bool if_thread_exsit(const pthread_t tid);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // !__UTIL_PTHREAD_H__
|
wotsen/util_phread
|
src/util_pthread.c
|
/**
* @file util_pthread.c
* @author 余王亮 (<EMAIL>)
* @brief
* @version 0.1
* @date 2019-11-02
*
* @copyright Copyright (c) 2019
*
*/
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/prctl.h>
#include "util_pthread.h"
/**
* @brief 创建线程
*
* @param tid 线程id
* @param stacksize 线程栈大小
* @param priority 线程优先级
* @param fn 线程人物接口
* @param arg 传递给线程的参数
* @return true 创建成功
* @return false 创建失败
*/
bool create_thread(pthread_t *tid, const size_t stacksize,
const int priority, thread_func fn, void *arg)
{
pthread_t _tid = INVALID_PTHREAD_TID;
pthread_attr_t attr;
struct sched_param param;
int min_pri = sched_get_priority_min(SCHED_RR);
int max_pri = sched_get_priority_max(SCHED_RR);
size_t _stacksize = stacksize;
int _pri = priority;
memset(&attr, 0, sizeof(attr));
memset(¶m, 0, sizeof(param));
/* 矫正线程栈 */
_stacksize = _stacksize < PTHREAD_STACK_MIN ? PTHREAD_STACK_MIN : _stacksize;
/* 矫正优先级 */
if (min_pri > _pri)
{
_pri = min_pri;
}
else if (max_pri < _pri)
{
_pri = max_pri;
}
else
{
// PASS
}
param.sched_priority = _pri;
if (pthread_attr_init(&attr) < 0)
{
printf("init thread attr error : %s", strerror(errno));
return false;
}
/* 设置线程分离 */
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) < 0)
{
printf("set attr detachstate error : %s", strerror(errno));
pthread_attr_destroy(&attr);
return false;
}
/* 设置调度策略FIFO */
if (pthread_attr_setschedpolicy(&attr, SCHED_RR) < 0)
{
printf("set attr schedpolicy error : %s\n", strerror(errno));
pthread_attr_destroy(&attr);
return false;
}
/* 设置线程优先级 */
if (pthread_attr_setschedparam(&attr, ¶m) < 0)
{
printf("set attr schedparam error : %s\n", strerror(errno));
pthread_attr_destroy(&attr);
return false;
}
/* 设置线程栈大小 */
if (pthread_attr_setstacksize(&attr, stacksize) < 0)
{
printf("set attr stacksize error : %s\n", strerror(errno));
pthread_attr_destroy(&attr);
return false;
}
/* 创建线程 */
if (pthread_create(&_tid, &attr, fn, arg) < 0)
{
printf("pthread_create failed : %s\n", strerror(errno));
pthread_attr_destroy(&attr);
return false;
}
if (NULL != tid)
{
*tid = _tid;
}
pthread_attr_destroy(&attr);
return true;
}
/**
* @brief 设置线程名称
*
* @param name
*/
void set_thread_name(const char *name)
{
char pname[MAX_THREAD_NAME_LEN + 1] = {'\0'};
pthread_t tid = pthread_self();
if (NULL != name)
{
sprintf(pname, "%s", (char *)name);
prctl(PR_SET_NAME, pname);
}
else
{
sprintf(pname, "p%zu", tid);
prctl(PR_SET_NAME, pname);
}
}
/**
* @brief 释放线程
*
* @param tid 线程号
* @return true 释放成功
* @return false 释放失败
*/
bool release_thread(const pthread_t tid)
{
if (if_thread_exsit(tid))
{
return pthread_cancel(tid) == 0;
}
return true;
}
/**
* @brief 检测线程存活
*
* @param tid 线程号
* @return true 线程存在
* @return false 线程不存在
*/
bool if_thread_exsit(const pthread_t tid)
{
if (INVALID_PTHREAD_TID == tid)
{
return false;
}
int pthread_kill_err = pthread_kill(tid, 0);
if (ESRCH == pthread_kill_err)
{
printf("task=[%ld] is not exist!\n", tid);
return false;
}
else if (EINVAL == pthread_kill_err)
{
printf("task=[%ld], send invalid signal to it!/n", tid);
return false;
}
else
{
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.