text
stringlengths 8
6.88M
|
|---|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x) ,left(NULL), right(NULL) {}
};
// vector<TreeNode *> generateTrees(int n){
// vector<vector<TreeNode *>> index;
// vector<TreeNode *> res(n,0);
// index.push_back(NULL);
// index.push_back(vector<TreeNode> oneline(1,1));
//
// for(int i=1;i<n;i++){
// TreeNode *p = new TreeNode(i);
// }
//
// return res[0];
// }
//
// TreeNode *copyAndAdd(TreeNode *root,int n){
// if(root == NULL) return NULL;
// TreeNode *p = new TreeNode(root->val+n);
// p->left = copyAndAdd(root->left,n);
// p->right = copyAndAdd(root->right,n);
// return p;
// }
// Not good
vector<TreeNode *> generateTrees(int n){
if(n==0) return helper(1,0);
return helper(1,n);
}
vector<TreeNode *> helper(int left, int right){
vector<TreeNode *> subTree;
if(left > right){
subTree.push_back(NULL);
return subTree;
}
for(int i=left;i<right;i++){
vector<TreeNode *> leftTree = helper(left,i-1);
vector<TreeNode *> rightTree = helper(i+1,right);
for(int j=0;j<=leftTree.size();j++){
for(int k=0;k<rightTree.size();k++){
TreeNode *node = new TreeNode(i);
node->left = leftTree[j];
node->right = rightTree[k];
subTree.push_back(node);
}
}
}
return subTree;
}
vector<TreeNode *> generateTrees(int n){
return *helper(1,n);
}
vector<TreeNode *>* helper(int left, int right){
vector<TreeNode *> *subTree;
if(left > right){
subTree.push_back(NULL);
return subTree;
}
for(int i=left;i<right;i++){
vector<TreeNode *> *leftTree = helper(left,i-1);
vector<TreeNode *> *rightTree = helper(i+1,right);
for(int j=0;j<=leftTree.size();j++){
for(int k=0;k<rightTree.size();k++){
TreeNode *node = new TreeNode(i);
node->left = (*leftTree)[j];
node->right = (*rightTree)rightTree[k];
subTree.push_back(node);
}
}
}
return subTree;
}
int main(){
int n;
cin >> n;
vector<TreeNode *> res;
res = generateTrees(n);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
string a,b,c;
int n;
cin >> n;
cin >> a;
cin >> b;
cin >> c;
ll ans = 0;
for (int i = 0; i < n; ++i) {
map<char, int> mp;
mp[a[i]] += 1;
mp[b[i]] += 1;
mp[c[i]] += 1;
vector<int> vec;
for (auto itr : mp) {
vec.push_back(itr.second);
}
sortd(vec);
ans += 3 - vec[0];
}
cout << ans << endl;
}
|
#include "pch.h"
#include "AudioSource.h"
#include "Core/ComponentFactory.h"
#include "System/AudioSystemWwise.h"
IMPLEMENT_COMPONENT_TYPEID(Hourglass::AudioSource)
void Hourglass::AudioSource::Start()
{
hg::g_AudioSystem.RegisterEntity(GetEntity(), "AudioSourceEntity");
}
void Hourglass::AudioSource::Shutdown()
{
hg::g_AudioSystem.UnRegisterEntity(GetEntity());
}
Hourglass::IComponent* Hourglass::AudioSource::MakeCopyDerived() const
{
AudioSource* copy = (AudioSource*)IComponent::Create(SID(AudioSource));
return copy;
}
void Hourglass::AudioSource::PostAudioEvent(uint64_t eventId) const
{
hg::g_AudioSystem.PostEvent(eventId, GetEntity());
}
|
#ifndef LINEARKALMANFILTER_H
#define LINEARKALMANFILTER_H
// http://arma.sourceforge.net/docs.html
#include "armadillo"
class LinearKalmanFilter {
public:
LinearKalmanFilter(
const arma::mat& stateTransitionMatrix,
const arma::mat& controlMatrix,
const arma::mat& observationMatrix,
const arma::mat& initialStateEstimate,
const arma::mat& initialCovarianceEstimate,
const arma::mat& processErrorEstimate,
const arma::mat& measurementErrorEstimate
);
void predict(const arma::mat& controlVector);
void observe(const arma::mat& measurementVector);
const arma::mat& getStateEstimate() const { return stateEstimate; }
private:
const arma::mat& stateTransitionMatrix;
const arma::mat& controlMatrix;
const arma::mat& observationMatrix;
const arma::mat& initialStateEstimate;
const arma::mat& initialCovarianceEstimate;
const arma::mat& processErrorEstimate;
const arma::mat& measurementErrorEstimate;
arma::mat predictedStateEstimate;
arma::mat predictedProbabilityEstimate;
arma::mat innovation;
arma::mat innovationCovariance;
arma::mat kalmanGain;
arma::mat stateEstimate;
arma::mat covarianceEstimate;
arma::mat* A;
};
#endif // LINEARKALMANFILTER_H
|
//知识点: 模拟,树状结构
/*
By:Luckyblock
题目要求:
给定 一棵树, 点有点权
给定两种操作:
1.修改某节点的点权
2.查询 距某节点 最近的 一个祖先,
满足 此节点 与 其祖先节点 点权值 最大公约数>1
分析题意:
由于此题数据 较弱
可以直接 暴力模拟
对于被查询节点, 暴力上跳
对于其每一个祖先 , 都与被查询节点进行比较
如果 最大公约数 >1 则直接输出
数据加强:
在初期状态和更改节点时,所有定点进行一次更新。之后所有1询问,用O(1)的方法得出。
A[i]的范围约20亿,而将其平方根后,质数约5000个。
先把A[i]全部质因数分解掉,更新的时候再计算就是了。
在这种情况下dfs树,准备好质数的栈组(一个质数准备一个栈,STL随便上),
先找到它的质因数栈的栈顶元素,最大的就是答案,一边把节点编号入栈,进行下一层dfs。
虽然质数很多,但是主要集中在2,3,5,7,11,13,所以时间复杂度平均很低。
*/
#include<cstdio>
#include<ctype.h>
const int MARX = 2e5+10;
//=============================================================
int n,k,num , fa[MARX],we[MARX];
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
int gcd(int a,int b){return b?gcd(b,a%b):a;}//求最大公约数
int inquiry(int now,int value)//暴力上跳 查询操作
{
if(now == 0) return -1;//到达根部上方
if(gcd(we[now],value) != 1) return now;//满足条件
return inquiry(fa[now],value);
}
//=============================================================
signed main()
{
n=read(), k=read();
for(int i=1; i<=n; i++) we[i] =read();
for(int i=1; i<n; i++)//建图
{
int u=read(),v=read();
fa[v] = u;
}
for(int i=1; i<=k; i++)//修改/回答询问
{
int type=read(),value1=read(),value2;
if(type == 1) printf("%d\n",inquiry(fa[value1],we[value1]));
else value2=read(),we[value1]=value2;
}
}
|
/*In this program we will be seeing about ARRAY in C++ Program*/
/*Array in a C++ Program is a kind of data type which is an user Defined data type, which is used to store a Collection of data which have same data type.*/
/*ADVANTAGE OF ARRAY : When used need to store many values of same data type, he/she can't ale to declear so many Varaile, instead of that he/she can Create an simple Array to store many datas of similar Data Type. */
/*DISADVANTAGE : Storeing datas of different data type is not possible in array*/
/*IN THIS LET SEE A COMPLETE ARRAY TO POINTER CONCEPT*/
/*Syntax to Pass an Array to Pointer is
DataType *PointerVariable;
DataType ArrayVariable[];
PointerVariable = ArrayVariable;
*/
/*Array element can be accessed by using the Array index value , thus array's are stored using index , Usually Array index starts with ZERO.*/
/*It is legal to access pointer array by *PointerVariable or by *(PointerVariable + i ) , i donates the index of the Pointer Variable.*/
/*It is legal to access ArrayVariable by ArrayVariable or by (ArrayVariable + i ) , i donates the index of the Array Variable.*/
/*including preprocessor / headerfile in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
/*Declaring an array of A*/
int arrA[] ={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9} ;
/*Declaring an Pointer Variable */
int *ptr ;
/*assinging an Array to a Pointer*/
ptr = arrA;
/*printing a data's present in an Pointer Variable *ptr */
cout<< "\nPrinting Array value using by Passing it to a Pointer Variable..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of *(ptr + " << i << " ) : " << *( ptr + i ) << endl ;
}
cout<<"\nPrinting Array value using Array Variable..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of arrA [ " << i << " ] : " << arrA [ i ] << endl ;
}
cout<<"\nPrinting Array value using Array Variable as Address..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of *(arrA + " << i << " ) : " << *(arrA + i ) << endl ;
}
}
|
#ifndef MSORT_H
#define MSORT_H
#include <cmath>
#include "comparison.h"
using namespace std;
template <class T, class Comparator>
void mergeSort (vector<T>& myArray, Comparator comp) {
mergeSortHelper(myArray, comp, 0, myArray.size()-1);
}
template <class T, class Comparator>
void mergeSortHelper (vector<T>& myArray, Comparator comp, int l, int r) {
if (l < r) {
int m = floor((l+r)/2);
mergeSortHelper(myArray, comp, l, m);
mergeSortHelper(myArray, comp, m+1, r);
int i=l, j=m+1, k=0;
vector<T> temp(r-l+1);
while (i<=m || j<=r) {
if (i<=m && (j>r || comp(myArray[i], myArray[j]))) {
temp[k] = myArray[i];
i++;
}
else {
temp[k] = myArray[j];
j++;
}
k++;
}
for (k=0; k<r-l+1; k++) {
myArray[k+l] = temp[k];
}
}
}
#endif
|
#ifndef DB_H
#define DB_H
#include "log.h"
#include <vector>
#include <QtSql/QSqlQuery>
#include <QObject>
using namespace std;
class Db : protected Log
{
public:
Db();
void connectSQL();
void selectNames();
void selectParts(QString name);
void selectConstruct(QString name);
static vector<vector<float> > things;
static vector<vector<vector<float>>> construct;
static vector<int> names;
static vector<int> parts;
void addPartSQL(QString name);
void savePartSQL(QString name, QString part, vector<vector<vector<QString>>> construct);
void deletePartSQL(QString name, QString part);
void resetPartsSQL(QString name);
void addName();
void removeName(QString name);
void saveColor(QString name, QString part, QString r, QString g, QString b);
void updateNormal(QString name, QString part, QString nX, QString nY, QString nZ);
void selectNormal(QString name);
static vector<vector<float>> normal;
private:
QString db = "3dg";
QString table = "poly";
void updateA(QString name, QString part, QString x, QString y, QString z);
void updateB(QString name, QString part, QString x, QString y, QString z);
void updateC(QString name, QString part, QString x, QString y, QString z);
void updateD(QString name, QString part, QString x, QString y, QString z);
void setConstruct(int size);
//void setThings();
void setNormal(int size);
};
#endif // DB_H
|
//
// Team_Pokemon.cpp for piscine in /home/selari_j/rendu/rush03_pool/s_team
//
// Made by Julien Selaries
// Login <[email protected]>
//
// Started on Sat Jan 24 17:15:29 2015 Julien Selaries
// Last update Sun Jan 25 23:24:49 2015 Tristan Roby
//
#include <iostream>
#include <fstream>
#include "Pokeplus.hh"
Pokeplus::Pokeplus()
{
this->ev = new t_ev;
this->iv = new t_iv;
this->ev->HP = 0;
this->ev->Atk = 0;
this->ev->Def = 0;
this->ev->SpA = 0;
this->ev->SpD = 0;
this->ev->Spe = 0;
this->hapiness = 0;
setRandIv();
}
Pokeplus::~Pokeplus()
{
delete[] this->ev;
delete[] this->iv;
}
void Pokeplus::setSizeTeam(int value)
{
this->size_team = value;
}
int Pokeplus::getSizeTeam()
{
return (this->size_team);
}
void Pokeplus::setRandIv()
{
this->iv->HP = 31;
this->iv->Atk = 31;
this->iv->Def = 31;
this->iv->SpA = 31;
this->iv->SpD = 31;
this->iv->Spe = 31;
}
int Pokeplus::getHapiness()
{
return (this->hapiness);
}
void Pokeplus::setHapiness(int value)
{
if (value < 0 ||
value > 255)
this->hapiness = value;
}
int Pokeplus::getPokemonId()
{
return (this->pokemon.ID);
}
/*
** IVs
*/
int Pokeplus::setIvHP(int value)
{
if (this->iv->HP += value > 31)
this->iv->HP = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvAtk(int value)
{
if (this->iv->Atk += value > 31)
this->iv->Atk = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvDef(int value)
{
if (this->iv->Def += value > 31)
this->iv->Def = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpA(int value)
{
if (this->iv->SpA += value > 31)
this->iv->SpA = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpD(int value)
{
if (this->iv->SpD += value > 31)
this->iv->SpD = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpe(int value)
{
if (this->iv->Spe += value > 31)
this->iv->Spe = value;
else
return (-1);
return (0);
}
int Pokeplus::getIvHP()
{
return (this->iv->HP);
}
int Pokeplus::getIvAtk()
{
return (this->iv->Atk);
}
int Pokeplus::getIvDef()
{
return (this->iv->Def);
}
int Pokeplus::getIvSpA()
{
return (this->iv->SpA);
}
int Pokeplus::getIvSpD()
{
return (this->iv->SpD);
}
int Pokeplus::getIvSpe()
{
return (this->iv->Spe);
}
/*
** EVs
*/
int Pokeplus::getAllEv()
{
return (this->ev->HP +
this->ev->Atk +
this->ev->Def +
this->ev->SpA +
this->ev->SpD +
this->ev->Spe);
}
int Pokeplus::setEvHP(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->HP + value <= 255)
{
this->ev->HP += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvAtk(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Atk + value <= 255)
{
this->ev->Atk += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvDef(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Def + value <= 255)
{
this->ev->Def += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpA(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->SpA + value <= 255)
{
this->ev->SpA += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpD(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->SpD + value <= 255)
{
this->ev->SpD += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpe(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Spe + value <= 255)
{
this->ev->Spe += value;
return (0);
}
return (-1);
}
int Pokeplus::getEvHP()
{
return (this->ev->HP);
}
int Pokeplus::getEvAtk()
{
return (this->ev->Atk);
}
int Pokeplus::getEvDef()
{
return (this->ev->Def);
}
int Pokeplus::getEvSpA()
{
return (this->ev->SpA);
}
int Pokeplus::getEvSpD()
{
return (this->ev->SpD);
}
int Pokeplus::getEvSpe()
{
return (this->ev->Spe);
}
int Pokeplus::setPokemon(int id, std::string xml)
{
Pokemon *new_p = new Pokemon(id, xml);
this->pokemon = *new_p;
return (0);
}
void Pokeplus::deletePokemon()
{
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Tomasz Jamroszczak [email protected]
*
*/
#ifndef DOM_DOMJILMESSAGEQUANTITIES_H
#define DOM_DOMJILMESSAGEQUANTITIES_H
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilobject.h"
#include "modules/pi/device_api/OpMessaging.h"
class DOM_JILMessageQuantities : public DOM_JILObject
{
public:
DOM_JILMessageQuantities() {}
~DOM_JILMessageQuantities() {}
virtual BOOL IsA(int type) { return type == DOM_TYPE_JIL_MESSAGEQUANTITIES || DOM_JILObject::IsA(type); }
static OP_STATUS Make(DOM_JILMessageQuantities*& new_obj, DOM_Runtime* runtime, int total, int read, int unread);
};
#endif // DOM_JIL_API_SUPPORT
#endif // DOM_DOMJILMESSAGEQUANTITIES_H
|
/*
========================================================================
DEVise Data Visualization Software
(c) Copyright 1992-1996
By the DEVise Development Group
Madison, Wisconsin
All Rights Reserved.
========================================================================
Under no circumstances is this software to be copied, distributed,
or altered in any way without prior permission from the DEVise
Development Group.
*/
/*
$Id: TDataBinary.c,v 1.26 1996/12/03 20:31:35 jussi Exp $
$Log: TDataBinary.c,v $
Revision 1.26 1996/12/03 20:31:35 jussi
Updated to reflect new TData interface.
Revision 1.25 1996/11/23 21:14:24 jussi
Removed failing support for variable-sized records.
Revision 1.24 1996/11/22 20:41:10 flisakow
Made variants of the TDataAscii classes for sequential access,
which build no indexes.
ReadRec() method now returns a status instead of void for every
class that has the method.
Revision 1.23 1996/11/18 22:50:32 jussi
Added estimation of total number of records in data set.
Revision 1.22 1996/10/08 21:49:09 wenger
ClassDir now checks for duplicate instance names; fixed bug 047
(problem with FileIndex class); fixed various other bugs.
Revision 1.21 1996/10/07 22:54:01 wenger
Added more error checking and better error messages in response to
some of the problems uncovered by CS 737 students.
Revision 1.20 1996/10/04 17:24:17 wenger
Moved handling of indices from TDataAscii and TDataBinary to new
FileIndex class.
Revision 1.19 1996/10/02 15:23:52 wenger
Improved error handling (modified a number of places in the code to use
the DevError class).
Revision 1.18 1996/08/27 19:03:27 flisakow
Added ifdef's around some informational printf's.
Revision 1.17 1996/08/04 21:59:54 beyer
Added UpdateLinks that allow one view to be told to update by another view.
Changed TData so that all TData's have a DataSource (for UpdateLinks).
Changed all of the subclasses of TData to conform.
A RecFile is now a DataSource.
Changed the stats buffers in ViewGraph to be DataSources.
Revision 1.16 1996/07/13 01:59:24 jussi
Moved initialization of i to make older compilers happy.
Revision 1.15 1996/07/05 15:19:15 jussi
Data source object is only deleted in the destructor. The dispatcher
now properly destroys all TData objects when it shuts down.
Revision 1.14 1996/07/03 23:13:42 jussi
Added call to _data->Close() in destructor. Renamed
_fileOkay to _fileOpen which is more accurate.
Revision 1.13 1996/07/02 22:48:33 jussi
Removed unnecessary dispatcher call.
Revision 1.12 1996/07/01 20:23:16 jussi
Added #ifdef conditionals to exclude the Web data source from
being compiled into the Attribute Projection executable.
Revision 1.11 1996/07/01 19:28:09 jussi
Added support for typed data sources (WWW and UNIXFILE). Renamed
'cache' references to 'index' (cache file is really an index).
Added support for asynchronous interface to data sources.
Revision 1.10 1996/06/27 18:12:41 wenger
Re-integrated most of the attribute projection code (most importantly,
all of the TData code) into the main code base (reduced the number of
modules used only in attribute projection).
Revision 1.9 1996/06/27 15:49:34 jussi
TDataAscii and TDataBinary now recognize when a file has been deleted,
shrunk, or has increased in size. The query processor is asked to
re-issue relevant queries when such events occur.
Revision 1.8 1996/06/04 19:58:48 wenger
Added the data segment option to TDataBinary; various minor cleanups.
Revision 1.7 1996/05/22 17:52:16 wenger
Extended DataSource subclasses to handle tape data; changed TDataAscii
and TDataBinary classes to use new DataSource subclasses to hide the
differences between tape and disk files.
Revision 1.6 1996/05/07 16:44:19 jussi
Cache file name now based on file alias (TData name). Added recPos
parameter to Decode() function call. Added support for a simple
index which is needed when streams are split into multiple
sub-streams (via matching values defined in the schema).
Revision 1.5 1996/05/05 03:08:15 jussi
Added support for composite attributes. Also added tape drive
support.
Revision 1.4 1996/04/20 19:56:58 kmurli
QueryProcFull now uses the Marker calls of Dispatcher class to call
itself when needed instead of being continuosly polled by the Dispatcher.
Revision 1.3 1996/04/16 20:38:52 jussi
Replaced assert() calls with DOASSERT macro.
Revision 1.2 1996/01/25 20:22:48 jussi
Improved support for data files that grow while visualization
is being performed.
Revision 1.1 1996/01/23 20:54:49 jussi
Initial revision.
*/
//#define DEBUG
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "Parse.h"
#include "TDataBinary.h"
#include "Exit.h"
#include "Util.h"
#include "DataSourceFileStream.h"
#include "DataSourceSegment.h"
#include "DataSourceTape.h"
#include "DevError.h"
#include "DataSeg.h"
#include "QueryProc.h"
#ifdef ATTRPROJ
# include "ApInit.h"
#else
# include "Init.h"
# include "DataSourceWeb.h"
#endif
/* We cache the first BIN_CONTENT_COMPARE_BYTES from the file.
The next time we start up, this cache is compared with what's in
the file to determine if they are the same file. */
static const int BIN_CONTENT_COMPARE_BYTES = 4096;
static char fileContent[BIN_CONTENT_COMPARE_BYTES];
static char indexFileContent[BIN_CONTENT_COMPARE_BYTES];
static char * srcFile = __FILE__;
TDataBinary::TDataBinary(char *name, char *type, char *param,
int recSize, int physRecSize)
: TData(name, type, param, recSize)
{
_physRecSize = physRecSize;
if (!strcmp(_type, "UNIXFILE")) {
_file = CopyString(_param);
#ifndef ATTRPROJ
} else if (!strcmp(_type, "WWW")) {
_file = MakeCacheFileName(_name, _type);
#endif
} else {
fprintf(stderr, "Invalid TData type: %s\n", _type);
DOASSERT(0, "Invalid TData type");
}
_fileOpen = true;
if (_data->Open("r") != StatusOk)
_fileOpen = false;
DataSeg::Set(NULL, NULL, 0, 0);
_bytesFetched = 0;
_lastPos = 0;
_currPos = 0;
_lastIncompleteLen = 0;
_totalRecs = 0;
float estNumRecs = _data->DataSize() / _physRecSize;
_indexP = new FileIndex((unsigned long)estNumRecs);
#if defined(DEBUG)
printf("Allocated %lu index entries\n", (unsigned long)estNumRecs);
#endif
Dispatcher::Current()->Register(this, 10, AllState, false, -1);
}
TDataBinary::~TDataBinary()
{
#if defined(DEBUG)
printf("TDataBinary destructor\n");
#endif
if (_fileOpen)
_data->Close();
Dispatcher::Current()->Unregister(this);
delete _indexP;
delete _indexFileName;
}
Boolean TDataBinary::CheckFileStatus()
{
// see if file is (still) okay
if (!_data->IsOk()) {
// if file used to be okay, close it
if (_fileOpen) {
Dispatcher::Current()->Unregister(this);
printf("Data stream %s is no longer available\n", _name);
_data->Close();
#ifndef ATTRPROJ
QueryProc::Instance()->ClearTData(this);
#endif
_fileOpen = false;
}
if (_data->Open("r") != StatusOk) {
// file access failure, get rid of index
_indexP->Clear();
_initTotalRecs = _totalRecs = 0;
_initLastPos = _lastPos = 0;
_lastIncompleteLen = 0;
return false;
}
printf("Data stream %s has become available\n", _name);
_fileOpen = true;
Dispatcher::Current()->Register(this, 10, AllState, false, -1);
}
return true;
}
int TDataBinary::Dimensions(int *sizeDimension)
{
sizeDimension[0] = _totalRecs;
return 1;
}
Boolean TDataBinary::HeadID(RecId &recId)
{
recId = 0;
return (_totalRecs > 0);
}
Boolean TDataBinary::LastID(RecId &recId)
{
if (!CheckFileStatus()) {
recId = _totalRecs - 1;
return false;
}
// see if file has grown
_currPos = _data->gotoEnd();
DOASSERT(_currPos >= 0, "Error finding end of data");
if (_currPos < _lastPos) {
#if defined(DEBUG)
printf("Rebuilding index...\n");
#endif
RebuildIndex();
#ifndef ATTRPROJ
QueryProc::Instance()->ClearTData(this);
#endif
} else if (_currPos > _lastPos) {
#if defined(DEBUG)
printf("Extending index...\n");
#endif
BuildIndex();
#ifndef ATTRPROJ
QueryProc::Instance()->RefreshTData(this);
#endif
}
recId = _totalRecs - 1;
return (_totalRecs > 0);
}
TData::TDHandle TDataBinary::InitGetRecs(RecId lowId, RecId highId,
Boolean asyncAllowed,
ReleaseMemoryCallback *callback)
{
DOASSERT((long)lowId < _totalRecs && (long)highId < _totalRecs
&& highId >= lowId, "Invalid record parameters");
TDataRequest *req = new TDataRequest;
DOASSERT(req, "Out of memory");
req->nextId = lowId;
req->endId = highId;
req->relcb = callback;
return req;
}
Boolean TDataBinary::GetRecs(TDHandle req, void *buf, int bufSize,
RecId &startRid, int &numRecs, int &dataSize)
{
DOASSERT(req, "Invalid request handle");
#if defined(DEBUG)
printf("TDataBinary::GetRecs buf = 0x%p\n", buf);
#endif
numRecs = bufSize / _recSize;
DOASSERT(numRecs > 0, "Not enough record buffer space");
if (req->nextId > req->endId)
return false;
int num = req->endId - req->nextId + 1;
if (num < numRecs)
numRecs = num;
ReadRec(req->nextId, numRecs, buf);
startRid = req->nextId;
dataSize = numRecs * _recSize;
req->nextId += numRecs;
_bytesFetched += dataSize;
return true;
}
void TDataBinary::DoneGetRecs(TDHandle req)
{
DOASSERT(req, "Invalid request handle");
delete req;
}
void TDataBinary::GetIndex(RecId id, int *&indices)
{
static int index[1];
index[0] = id;
indices = index;
}
int TDataBinary::GetModTime()
{
if (!CheckFileStatus())
return -1;
return _data->GetModTime();
}
char *TDataBinary::MakeIndexFileName(char *name, char *type)
{
char *fname = StripPath(name);
int nameLen = strlen(Init::WorkDir()) + 1 + strlen(fname) + 1;
char *fn = new char[nameLen];
sprintf(fn, "%s/%s", Init::WorkDir(), fname);
return fn;
}
void TDataBinary::Initialize()
{
_indexFileName = MakeIndexFileName(_name, _type);
if (!CheckFileStatus())
return;
if (_data->isBuf()) {
BuildIndex();
return;
}
if (!_indexP->Initialize(_indexFileName, _data, this, _lastPos,
_totalRecs).IsComplete()) goto error;
_initTotalRecs = _totalRecs;
_initLastPos = _lastPos;
/* continue to build index */
BuildIndex();
return;
error:
/* recover from error by building index from scratch */
#if defined(DEBUG)
printf("Rebuilding index...\n");
#endif
RebuildIndex();
}
void TDataBinary::Checkpoint()
{
if (!CheckFileStatus()) {
printf("Cannot checkpoint %s\n", _name);
return;
}
if (_data->isBuf()) {
BuildIndex();
return;
}
printf("Checkpointing %s: %ld total records, %ld new\n", _name,
_totalRecs, _totalRecs - _initTotalRecs);
if (_lastPos == _initLastPos && _totalRecs == _initTotalRecs)
/* no need to checkpoint */
return;
if (!_indexP->Checkpoint(_indexFileName, _data, this, _lastPos,
_totalRecs).IsComplete()) goto error;
_currPos = _data->Tell();
return;
error:
_currPos = _data->Tell();
}
/* Build index for the file. This code should work when file size
is extended dynamically. Before calling this function, position
should be at the last place where file was scanned. */
void TDataBinary::BuildIndex()
{
char physRec[_physRecSize];
char recBuf[_recSize];
int oldTotal = _totalRecs;
_currPos = _lastPos - _lastIncompleteLen;
// First go to last valid position of file
if (_data->Seek(_currPos, SEEK_SET) < 0) {
reportErrSys("fseek");
return;
}
_lastIncompleteLen = 0;
while(1) {
int len = 0;
len = _data->Fread(physRec, 1, _physRecSize);
if (!len)
break;
DOASSERT(len >= 0, "Cannot read data stream");
if (len == _physRecSize) {
if (Decode(recBuf, _currPos / _physRecSize, physRec)) {
_indexP->Set(_totalRecs++, _currPos);
} else {
#if defined(DEBUG)
printf("Ignoring invalid or non-matching record\n");
#endif
}
_lastIncompleteLen = 0;
} else {
#if defined(DEBUG)
printf("Ignoring incomplete record (%d bytes)\n", len);
#endif
_lastIncompleteLen = len;
}
_currPos += len;
}
// last position is > current position because TapeDrive advances
// bufferOffset to the next block, past the EOF, when tape file
// ends
_lastPos = _data->Tell();
DOASSERT(_lastPos >= _currPos, "Incorrect file position");
#ifdef DEBUG
printf("Index for %s: %ld total records, %ld new\n", _name,
_totalRecs, _totalRecs - oldTotal);
#endif
if (_totalRecs <= 0)
fprintf(stderr, "No valid records for data stream %s\n"
" (check schema/data correspondence)\n", _name);
}
/* Rebuild index */
void TDataBinary::RebuildIndex()
{
InvalidateIndex();
_indexP->Clear();
_initTotalRecs = _totalRecs = 0;
_initLastPos = _lastPos = 0;
_lastIncompleteLen = 0;
BuildIndex();
}
TD_Status TDataBinary::ReadRec(RecId id, int numRecs, void *buf)
{
#if defined(DEBUG)
printf("TDataBinary::ReadRec %ld,%d,0x%p\n", id, numRecs, buf);
#endif
char *ptr = (char *)buf;
for(int i = 0; i < numRecs; i++) {
long recloc = _indexP->Get(id + i);
// Note that if the data source is a tape, we _always_ seek, even if
// we think we're already at the right place. This was copied from
// the previously-existing code. RKW 5/21/96.
if (_data->isTape() || (_currPos != recloc)) {
if (_data->Seek(recloc, SEEK_SET) < 0) {
reportErrSys("fseek");
DOASSERT(0, "Cannot perform file seek");
}
_currPos = recloc;
}
if (_data->Fread(ptr, _physRecSize, 1) != 1) {
reportErrSys("fread");
DOASSERT(0, "Cannot read from file");
}
Boolean valid = Decode(ptr, _currPos / _physRecSize, ptr);
DOASSERT(valid, "Inconsistent validity flag");
ptr += _recSize;
_currPos += _physRecSize;
}
return TD_OK;
}
void TDataBinary::WriteRecs(RecId startRid, int numRecs, void *buf)
{
DOASSERT(!_data->isTape(), "Writing to tape not supported yet");
_totalRecs += numRecs;
_indexP->Set(_totalRecs - 1, _lastPos);
int len = numRecs * _physRecSize;
if (_data->append(buf, len) != len) {
reportErrSys("tapewrite");
DOASSERT(0, "Cannot append to file");
}
_lastPos = _data->Tell();
_currPos = _lastPos;
}
void TDataBinary::WriteLine(void *rec)
{
WriteRecs(0, 1, rec);
}
void TDataBinary::Cleanup()
{
Checkpoint();
if (_data->isTape())
_data->printStats();
}
void TDataBinary::PrintIndices()
{
int cnt = 0;
for(long i = 0; i < _totalRecs; i++) {
printf("%ld ", _indexP->Get(i));
if (cnt++ == 10) {
printf("\n");
cnt = 0;
}
}
printf("\n");
}
|
//
// Created by fab on 20/12/2020.
//
#ifndef DUMBERENGINE_IPOSTRENDERING_HPP
#define DUMBERENGINE_IPOSTRENDERING_HPP
class IPostRendering
{
public:
virtual void postDraw() = 0;
};
#endif //DUMBERENGINE_IPOSTRENDERING_HPP
|
#pragma once
#include "SquareGrid.h"
SquareGrid::SquareGrid()
{
std::srand(std::time(NULL));
}
SquareGrid::~SquareGrid()
{
delete[] mTiles;
delete[] mNeighbors;
}
bool SquareGrid::init(/*std::string file*/ std::vector<SpawnerStruct>& enemySpawners)
{
startPos = 0;
mWidth = 10;
mHeight = 10;
mTileWidth = 125;
mTileHeight = 65;
mTiles = new uint8[mWidth* mHeight];
mNeighbors = new int[mWidth* mHeight];
LoadGrid(enemySpawners);
BreadthFirst();
return true;
}
int SquareGrid::getTileWidth()
{
return mTileWidth;
}
int SquareGrid::getTileHeight()
{
return mTileHeight;
}
int SquareGrid::getGridWidth()
{
return mWidth;
}
int SquareGrid::getGridHeight()
{
return mHeight;
}
void SquareGrid::update(float deltaTime)
{
}
void SquareGrid::draw(sf::RenderWindow& window)
{
sf::RectangleShape temp(sf::Vector2f(mTileWidth, mTileHeight));
temp.setPosition(0,0);
temp.setOrigin(mTileWidth/2.0f, mTileHeight/2.0f);
temp.setFillColor(sf::Color::White);
//Need to check if the tile is in the window
for(int i = 0; i < (mWidth* mHeight); i++)
{
temp.setFillColor(sf::Color::White);
temp.setPosition(((i%mWidth)*mTileWidth)+(mTileWidth/2), ((i/mWidth)*mTileHeight)+(mTileHeight/2));
if(((mTiles[i] & TILENUM) == 0))
{
temp.setFillColor(sf::Color::Green);
}
if(((mTiles[i] & TILENUM) == 1))
{
temp.setFillColor(sf::Color::Blue);
}
if(((mTiles[i] & TILENUM) == 2))
{
temp.setFillColor(sf::Color::Yellow);
}
if(((mTiles[i] & TILENUM) == 3))
{
temp.setFillColor(sf::Color::Red);
}
window.draw(temp);
}
//std::cout << std::endl;
}
void SquareGrid::BreadthFirst()
{
std::queue<int> fronter = std::queue<int>();
std::set<int> checked =std::set<int>();
fronter.push(endPos);
mNeighbors[endPos] = endPos;
checked.insert(endPos);
int current;
while(!fronter.empty())
{
current = fronter.front();
fronter.pop();
//Check to see if the node isnt in the first column
if(current% mWidth != 0)
{
addToFrontier(current, current-1, fronter, checked);
}
//Check to see if the node isnt in the last col
if(current % mWidth != mWidth -1)
{
addToFrontier(current, current+1, fronter, checked);
}
//Check to see if the node is in the first row
if(current / mWidth != 0)
{
addToFrontier(current, current-mWidth, fronter, checked);
}
//check to see if the node is in the last row
if(current / mHeight != mHeight-1)
{
addToFrontier(current, current+mWidth, fronter, checked);
}
}
}
void SquareGrid::LoadGrid(std::vector<SpawnerStruct>& enemySpawners)
{
int temp [100] = {0, 3, 1, 0, 1, 1, 1, 1, 1, 1,
1, 3, 1, 3, 1, 1, 1, 1, 1, 1,
1, 3, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 3, 3, 3, 1, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1,
1, 3, 3, 1, 1, 1, 1, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1,
0, 1, 1, 1, 1, 1, 1, 3, 1, 2};
for (int j = 0; j < (mWidth* mHeight); j++)
{
mNeighbors[j] = -1;
}
for(int i = 0; i < (mWidth* mHeight); i++)
{
uint8 t;
switch (temp[i])
{
case 0:
//Tile number plus walkable shifted over by 4 bits
t = temp[i] + WALKABLE;
mTiles[i] = t;
SpawnerStruct s;
s.spawner = new SpawnerFor<Enemy>();
s.tileLocation = i;
enemySpawners.push_back(s);
break;
case 1:
t = temp[i] + WALKABLE + BUILDABLE;
mTiles[i] = t;
break;
case 2:
t = temp[i] + WALKABLE;
mTiles[i] = t;
endPos = i;
break;
case 3:
t = temp[i];
mTiles[i] = t;
endPos = i;
break;
}
}
}
void SquareGrid::addToFrontier(int current, int toAdd, std::queue<int>& fronter, std::set<int>& checked)
{
if(((mTiles[toAdd] & WALKABLE) != 0) && (checked.find(toAdd) == checked.end()))
{
fronter.push(toAdd);
mNeighbors[toAdd] = current;
checked.insert(toAdd);
}
}
void SquareGrid::changeTile(int tileNum)
{
mTiles[tileNum] = 3;
BreadthFirst();
}
sf::Vector2f SquareGrid::getPosOfTile(int tileNum)
{
return sf::Vector2f(((tileNum%mWidth)*mTileWidth)+(mTileWidth/2), ((tileNum/mWidth)*mTileHeight)+(mTileHeight/2));
}
sf::Vector2f SquareGrid::getPosInTile(int tileNum)
{
sf::Vector2f temp;
temp.x = (std::rand() % mTileWidth) + ((tileNum%mWidth)*mTileWidth);
temp.y = (std::rand() % mTileHeight) + ((tileNum/mWidth)*mTileHeight);
return temp;
}
void SquareGrid::CalculatePath(MovableObject* e)
{
//Figure out start position of a passed in enemy
int pos = ((int)e->getPos().x/mTileWidth) + ((int)e->getPos().y/mTileHeight)*mHeight;
//std::cout << "Pos: " << e->getPos().x << ", " << e->getPos().y << std::endl;
e->clearInput();
//For each part of the path send a move command to the enemy
while (pos != endPos)
{
//std::cout << "Path: " << pos << "->" << mNeighbors[pos] << std::endl;
//Get the next part on the path and calculate what position to move to
e->addInput(new MoveCommand((mNeighbors[pos]%mWidth)*mTileWidth + (mTileWidth/2),
(mNeighbors[pos]/mHeight)*mTileHeight+ (mTileHeight/2)));
pos = mNeighbors[pos];
}
}
//Gives the global
int SquareGrid::checkClick(sf::Vector2i mouseClick)
{
//check to see if the click was in the grid
if(mouseClick.x > 0 && mouseClick.y > 0 && mouseClick.x < mWidth*mTileWidth && mouseClick.y < mHeight*mTileHeight)
{
changeTile((mouseClick.x/mTileWidth) + (mouseClick.y/mTileHeight)*mHeight);
return (mouseClick.x/mTileWidth) + (mouseClick.y/mTileHeight)*mHeight;
}
return -1;
}
|
#ifndef LocalizationSimulator_h
#define LocalizationSimulator_h
// standard includes
#include <cmath>
#include <memory>
// system includes
#include <Eigen/Dense>
#include <actionlib/server/simple_action_server.h>
#include <eigen_conversions/eigen_msg.h>
#include <nav_msgs/OccupancyGrid.h>
#include <ros/ros.h>
#include <spellbook/msg_utils/msg_utils.h>
#include <spellbook/utils/RunUponDestruction.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
// project includes
#include <rcta/TeleportAndaliteCommandAction.h>
class LocalizationSimulator
{
public:
LocalizationSimulator();
enum MainResult
{
SUCCESS,
FAILED_TO_INITIALIZE
};
int run();
private:
bool initialize();
void publish_costmap();
ros::NodeHandle nh_;
ros::NodeHandle ph_;
std::string action_name_;
std::string world_frame_nwu_name_;
std::string world_frame_ned_name_;
std::string robot_frame_nwu_name_;
std::string robot_frame_ned_name_;
std::string robot_odometry_frame_ned_name_;
tf::TransformBroadcaster broadcaster_;
tf::TransformListener listener_;
Eigen::Affine3d world_to_robot_;
Eigen::Affine3d footprint_to_robot_;
typedef actionlib::SimpleActionServer<rcta::TeleportAndaliteCommandAction> TeleportAndaliteCommandActionServer;
std::unique_ptr<TeleportAndaliteCommandActionServer> as_;
bool publish_costmap_;
std::string costmap_bagfile_;
nav_msgs::OccupancyGrid::Ptr last_costmap_msg_;
ros::Publisher costmap_pub_;
ros::Time last_costmap_pub_time_;
ros::Rate costmap_pub_rate_;
void goal_callback();
void preempt_callback();
bool transform(const std::string& target, const std::string& source, Eigen::Affine3d& transform);
};
#endif
|
/*
* struct.h
*
* Created on: 2021. 9. 25.
* Author: dhjeong
*/
#ifndef RAIIANDMEM_STRUCT_H_
#define RAIIANDMEM_STRUCT_H_
#include <boost/shared_ptr.hpp>
#include <iostream>
class DataInfo {
public:
DataInfo() {
size = 0;
permission = 0;
}
DataInfo(const std::string &sName, size_t sSize, int sPermission) {
name = sName;
size = sSize;
permission = sPermission;
}
~DataInfo() {
std::cout << "Destroy " << name << std::endl;
}
std::string name;
size_t size;
int permission;
};
class A {
int *data;
std::shared_ptr<A> other;
public:
A() {
data = new int[100];
std::cout << "자원을 획득함!" << std::endl;
}
~A() {
std::cout << "소멸자 호출!" << std::endl;
delete[] data;
}
void set_other(std::shared_ptr<A> o) {
other = o;
}
int getCount() {
return other.use_count();
}
};
#endif /* RAIIANDMEM_STRUCT_H_ */
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
std::vector<int> vs1;
int n = 5;
for (int i = 0;i < n;i++) {
vs1.push_back(i);
}
vs1.pop_back();
vs1.insert(vs1.begin(), 100);
vs1.insert(vs1.begin()+3, 200);
vs1.insert(vs1.end() ,300);
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ": " << vs1[i] << endl;
}
cout << "find...." << endl;
std::vector<int>::iterator it = find(vs1.begin(),vs1.end(),3);
if (it == vs1.end() ) {
cout << "not found " << endl;
} else {
cout << "found at index " << (it - vs1.begin()) << endl;
vs1.insert(it,60000);
}
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ": " << vs1[i] << endl;
}
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Простой пример использования логических значений
// При каких условиях можно поплавать?
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
using namespace std;
int main() {
cout.setf(ios::boolalpha);
bool a; // Вода холодная
bool b = true; // Я плаваю?
cout << "Вода холодная? (1/0)" << endl;
cin >> a;
/*
if (!a) { // Если а == 1
b = !b; // То b - true
}
else {
b = b; // Иначе b == false
}
cout << "Плаваем или нет? - "<< b << endl;
*/
cout << (!a && b) << "\n";
return 0;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include "Graph.h"
#include <map>
#include <iomanip>
#include <vector>
#include <algorithm>
Graph::Graph(ofstream * flog)
{
this->mList = NULL; // mList[from vetex] = map<to vertex, weigth>
this->vertex = NULL; // vetex[index] = CityData *
this->mstMatrix = NULL; // MST
this->flog = flog;
}
Graph::~Graph()
{
}
bool Graph::Build(AVLTree * tree, int size)
{
if (this->mList != NULL) {
delete[] this->mList;
delete[] this->vertex;
delete[] this->set;
delete[] this->mstMatrix;
this->mList = NULL; // mList[from vetex] = map<to vertex, weigth>
this->vertex = NULL; // vetex[index] = CityData *
this->mstMatrix = NULL;
this->set = NULL;
this->idx = 0;
}
AVLNode* root = tree->Getroot();
if (size == 0) // Return false, if tree is empty
return false;
this->mList = new map<int, CityData *>[size];
this->vertex = new CityData*[size];
InOrderInit(root);
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++) {
mList[row].insert(make_pair(col, vertex[col]));
}
return true;
}
bool Graph::Print_GP(int size)
{
(*flog).setf(ios::left);
if (vertex == NULL)
return false;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++)
*flog << setw(3) << GetDistance(vertex[row], vertex[col]);
*flog << endl;
}
return true;
}
bool Graph::Print_MST(int size)
{
if (size == 0)
return false;
int total = 0; // sum of edges
int* cnt = new int[size];
int* check = new int[size];
for (int i = 0; i < size; i++) { // Init the array
cnt[i] = 0; check[i] = 0;
}
for (int i = 0; i < size-1; i++) { // Search start point and end point
cnt[mstMatrix[i].second.first] += 1;
cnt[mstMatrix[i].second.second] += 1;
}
int start = 0; // Set start point
for (int i = 0; i < size; i++) {
if (cnt[i] == 1) {
start = i;
break;
}
}
int end = 0; // Set end point
for (int i = 0; i < size; i++) {
if (cnt[i] == 1)
if (start < i)
end = i;
else if (start > i) {
end = start;
start = i;
}
}
int key = start;
int next_key = 0;
for (int j = 0; j < size - 1; j++) {
for (int i = 0; i < size - 1; i++) { //n(mstMatrix) = 9
if (key == this->mstMatrix[i].second.first && check[key] < 2 && key!=end) {
*flog << "( " << this->vertex[this->mstMatrix[i].second.first]->Getname()
<< ", " << this->vertex[this->mstMatrix[i].second.second]->Getname()
<< " ), " << this->mstMatrix[i].first << endl;
total += this->mstMatrix[i].first;
check[this->mstMatrix[i].second.first]++; check[this->mstMatrix[i].second.second]++;
key = this->mstMatrix[i].second.second;
}
else if (key == this->mstMatrix[i].second.second && check[key] < 2 && key!=end) {
*flog << "( " << this->vertex[this->mstMatrix[i].second.second]->Getname()
<< ", " << this->vertex[this->mstMatrix[i].second.first]->Getname()
<< " ), " << this->mstMatrix[i].first << endl;
total += this->mstMatrix[i].first;
check[this->mstMatrix[i].second.first]++; check[this->mstMatrix[i].second.second]++;
key = this->mstMatrix[i].second.first;
}
}
}
*flog << "Total: " << (total) << endl;
return true;
}
bool Graph::Kruskal(int size)
{
if (size == 0 || size == 1) return false;
int i = 0, j = 0, weight = 0;
vector<pair<int, pair<int, int>>> v;
make_set(size); // make cycle table
// Phase 1: Sort graph edges in ascending order of weight
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size; j++) {
weight = GetDistance(vertex[i], vertex[j]);
v.push_back(make_pair(weight, make_pair(i, j)));
}
sort(v.begin(), v.end());
// Phase 2: Select edges that don't form a cycle from the list in order
// Phase 2-1: Choose a lower weight
mstMatrix = new pair<int, pair<int, int>>[size - 1];
int cnt = 0;
// Phase 2-2: Add, If cycle does not occur
for (int i = 0; i < v.size(); i++) {
if (!check(v[i].second.first, v[i].second.second)) {
union_set(v[i].second.first, v[i].second.second);
mstMatrix[cnt] = v[i];
cnt++;
}
}
/*for (int i = 0; i < v.size(); i++)
cout << v[i].first << " " << v[i].second.first << " " << v[i].second.second << endl;*/
return true;
}
void Graph::make_set(int size)
{
this ->set = new int[size];
for (int i = 0; i < size; i++)
set[i] = i;
}
void Graph::union_set(int x, int y)
{
x = find(x);
y = find(y);
if(x<y) set[y] = x;
else set[x] = y;
}
int Graph::find(int x) // Get
{
if (set[x] == x) return x;
return find(set[x]);
}
void Graph::InOrderInit(AVLNode* node)
{
if (node != NULL)
{
InOrderInit(node->GetLeft());
vertex[idx++] = node->GetCityData();
InOrderInit(node->GetRight());
}
}
int Graph::GetDistance(CityData * from, CityData * to)
{
int distance = 0;
if (from->GetLocationId() > to->GetLocationId()) distance = from->GetLocationId() - to->GetLocationId();
else distance = to->GetLocationId() - from->GetLocationId();
return distance;
}
int Graph::check(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return 1;
else return 0;
}
|
// Created on: 1994-09-02
// Created by: Bruno DUMORTIER
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ProjLib_ProjectOnPlane_HeaderFile
#define _ProjLib_ProjectOnPlane_HeaderFile
#include <Adaptor3d_Curve.hxx>
#include <gp_Ax3.hxx>
#include <gp_Dir.hxx>
#include <GeomAbs_CurveType.hxx>
#include <GeomAdaptor_Curve.hxx>
#include <Adaptor3d_Curve.hxx>
#include <GeomAbs_Shape.hxx>
#include <TColStd_Array1OfReal.hxx>
class gp_Pnt;
class gp_Vec;
class gp_Lin;
class gp_Circ;
class gp_Elips;
class gp_Hypr;
class gp_Parab;
class Geom_BezierCurve;
class Geom_BSplineCurve;
//! Class used to project a 3d curve on a plane. The
//! result will be a 3d curve.
//!
//! You can ask the projected curve to have the same
//! parametrization as the original curve.
//!
//! The projection can be done along every direction not
//! parallel to the plane.
class ProjLib_ProjectOnPlane : public Adaptor3d_Curve
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
Standard_EXPORT ProjLib_ProjectOnPlane();
//! The projection will be normal to the Plane defined
//! by the Ax3 <Pl>.
Standard_EXPORT ProjLib_ProjectOnPlane(const gp_Ax3& Pl);
//! The projection will be along the direction <D> on
//! the plane defined by the Ax3 <Pl>.
//! raises if the direction <D> is parallel to the
//! plane <Pl>.
Standard_EXPORT ProjLib_ProjectOnPlane(const gp_Ax3& Pl, const gp_Dir& D);
//! Shallow copy of adaptor
Standard_EXPORT virtual Handle(Adaptor3d_Curve) ShallowCopy() const Standard_OVERRIDE;
//! Sets the Curve and perform the projection.
//! if <KeepParametrization> is true, the parametrization
//! of the Projected Curve <PC> will be the same as
//! the parametrization of the initial curve <C>.
//! It means: proj(C(u)) = PC(u) for each u.
//! Otherwise, the parametrization may change.
Standard_EXPORT void Load (const Handle(Adaptor3d_Curve)& C, const Standard_Real Tolerance, const Standard_Boolean KeepParametrization = Standard_True);
Standard_EXPORT const gp_Ax3& GetPlane() const;
Standard_EXPORT const gp_Dir& GetDirection() const;
Standard_EXPORT const Handle(Adaptor3d_Curve)& GetCurve() const;
Standard_EXPORT const Handle(GeomAdaptor_Curve)& GetResult() const;
Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE;
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! If necessary, breaks the curve in intervals of
//! continuity <S>. And returns the number of
//! intervals.
Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Stores in <T> the parameters bounding the intervals of continuity <S>.
//!
//! The array must provide enough room to accommodate
//! for the parameters. i.e. T.Length() > NbIntervals()
Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns a curve equivalent of <me> between
//! parameters <First> and <Last>. <Tol> is used to
//! test for 3d points confusion.
//! If <First> >= <Last>
Standard_EXPORT Handle(Adaptor3d_Curve) Trim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real Period() const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT gp_Pnt Value (const Standard_Real U) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt& P) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve with its
//! first derivative.
//! Raised if the continuity of the current interval
//! is not C1.
Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first and second
//! derivatives V1 and V2.
//! Raised if the continuity of the current interval
//! is not C2.
Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first, the second
//! and the third derivative.
//! Raised if the continuity of the current interval
//! is not C3.
Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3) const Standard_OVERRIDE;
//! The returned vector gives the value of the derivative for the
//! order of derivation N.
//! Raised if the continuity of the current interval
//! is not CN.
//! Raised if N < 1.
Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE;
//! Returns the parametric resolution corresponding
//! to the real space resolution <R3d>.
Standard_EXPORT Standard_Real Resolution (const Standard_Real R3d) const Standard_OVERRIDE;
//! Returns the type of the curve in the current
//! interval : Line, Circle, Ellipse, Hyperbola,
//! Parabola, BezierCurve, BSplineCurve, OtherCurve.
Standard_EXPORT GeomAbs_CurveType GetType() const Standard_OVERRIDE;
Standard_EXPORT gp_Lin Line() const Standard_OVERRIDE;
Standard_EXPORT gp_Circ Circle() const Standard_OVERRIDE;
Standard_EXPORT gp_Elips Ellipse() const Standard_OVERRIDE;
Standard_EXPORT gp_Hypr Hyperbola() const Standard_OVERRIDE;
Standard_EXPORT gp_Parab Parabola() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer Degree() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsRational() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbPoles() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbKnots() const Standard_OVERRIDE;
//! Warning ! this will NOT make a copy of the
//! Bezier Curve : If you want to modify
//! the Curve please make a copy yourself
//! Also it will NOT trim the surface to
//! myFirst/Last.
Standard_EXPORT Handle(Geom_BezierCurve) Bezier() const Standard_OVERRIDE;
//! Warning ! this will NOT make a copy of the
//! BSpline Curve : If you want to modify
//! the Curve please make a copy yourself
//! Also it will NOT trim the surface to
//! myFirst/Last.
Standard_EXPORT Handle(Geom_BSplineCurve) BSpline() const Standard_OVERRIDE;
protected:
void GetTrimmedResult(const Handle(Geom_Curve)& theProjCurve);
Standard_Boolean BuildParabolaByApex(Handle(Geom_Curve)& theGeomParabolaPtr);
Standard_Boolean BuildHyperbolaByApex(Handle(Geom_Curve)& theGeomParabolaPtr);
void BuildByApprox(const Standard_Real theLimitParameter);
private:
Handle(Adaptor3d_Curve) myCurve;
gp_Ax3 myPlane;
gp_Dir myDirection;
Standard_Boolean myKeepParam;
Standard_Real myFirstPar;
Standard_Real myLastPar;
Standard_Real myTolerance;
GeomAbs_CurveType myType;
Handle(GeomAdaptor_Curve) myResult;
Standard_Boolean myIsApprox;
};
#endif // _ProjLib_ProjectOnPlane_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef PRINT_PROGRESS_DIALOG_H
#define PRINT_PROGRESS_DIALOG_H
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick_toolkit/widgets/OpLabel.h"
# if defined _PRINT_SUPPORT_ && defined GENERIC_PRINTING && defined QUICK_TOOLKIT_PRINT_PROGRESS_DIALOG
class PrintProgressDialog : public Dialog
{
public:
PrintProgressDialog(OpBrowserView* browser_view) : m_label(0), m_browser_view(browser_view) {}
void OnInitVisibility()
{
m_label = (OpLabel*) GetWidgetByName("Message_label");
SetPage(1);
}
void GetButtonInfo(INT32 index, OpInputAction*& action, OpString& text, BOOL& is_enabled, BOOL& is_default, OpString8& name)
{
is_enabled = TRUE;
if (index == 0)
{
is_default = TRUE;
action = GetCancelAction();
text.Set(GetCancelText());
name.Set(WIDGET_NAME_BUTTON_CANCEL);
}
}
void SetPage( INT32 page )
{
if (m_label)
{
OpString message;
TRAPD(rc,g_languageManager->GetStringL(Str::SI_PRINTING_PAGE_TEXT,message));
message.AppendFormat(UNI_L(" %d"), page);
m_label->SetLabel( message.CStr(), TRUE );
m_label->Sync();
}
}
void OnCancel()
{
m_browser_view->PrintProgressDialogDone(); // Dialog destroyed and no longer valid
Dialog::OnCancel();
}
virtual BOOL GetModality() { return TRUE; }
virtual BOOL GetIsBlocking() { return FALSE; }
virtual Type GetType() { return DIALOG_TYPE_PRINT_PROGRESS; }
virtual const char* GetWindowName() { return "Print Progress Dialog"; }
virtual BOOL HasCenteredButtons() { return TRUE; }
INT32 GetButtonCount() { return 1; };
private:
OpLabel* m_label;
OpBrowserView* m_browser_view;
};
#endif // _PRINT_SUPPORT_ && GENERIC_PRINTING && QUICK_TOOLKIT_PRINT_PROGRESS_DIALOG
#endif // PRINT_PROGRESS_DIALOG_H
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5