text
stringlengths
8
6.88M
#include "ShaderManager.h" namespace liman { ShaderManager::~ShaderManager() { m_shaders.clear(); m_shaderList.clear(); } bool ShaderManager::CreateShader(std::string shaderStr) { auto findIt = m_shaders.find(shaderStr); if (findIt == m_shaders.end()) { LOG("ShaderManager", "Creating shader " + shaderStr); Shader* pShader = new Shader("/Users/matthewpoletin/Documents/Projects/Personal/Liman/" + liman::g_pApp->GetResCahe()->GetPath("Shaders") + shaderStr); m_shaders.insert(std::make_pair(shaderStr, pShader)); m_shaderList.push_back(shaderStr); return true; } else { LOG("ShaderManager", "Specified shader " + shaderStr + " already exists"); return false; } } bool ShaderManager::AddShader(std::string shaderName, Shader* pShader) { // ToDo: Write map insertion return true; } Shader* ShaderManager::GetShader(std::string shaderStr) { auto findIt = m_shaders.find(shaderStr); if (findIt == m_shaders.end()) { LOG("ShaderManager", "Specified shader " + shaderStr + " was not found"); return nullptr; } else { return findIt->second; } } bool ShaderManager::DeleteShader(std::string shaderName) { auto findIt = m_shaders.find(shaderName); if (findIt == m_shaders.end()) { LOG("ShaderManager", "Specified shader " + shaderName + " was not found"); return false; } else { m_shaders.erase(shaderName); m_shaderList.remove(shaderName); return true; } } }
#include "../inc.h" struct Solution1 { //O(N^2) int solve(long long c, const vector<long long> & a, const vector<long long> & b){ C = c; A = a; B = b; int ret = 0; for (size_t i = 0; i < A.size(); ++i) if (canFrom(i)) ++ret; return ret; } private: bool canFrom(size_t f) const{ long long cur = 0; for (size_t i = 0; i < A.size(); ++i){ const size_t idx = (i + f) % A.size(); cur += A[idx]; if (cur > C) cur = C; cur -= B[idx]; if (cur < 0) return false; } return true; } long long C; vector<long long> A, B; }; struct Solution2 { //O(N) int solve(long long C, const vector<long long> & A, const vector<long long> & B){ vector<long long> d(A.size()); //first round int i = A.size() - 1, ret = 0; long long m = 0; for (; i >= 0; --i){ m += B[i]; if (m > C) return 0; if (m > A[i]) d[i] = (m -= A[i]); else{ d[i] = m = 0; ++ret; } } //second round i = A.size() - 1; for (; i >= 0; --i){ m += B[i]; if (m > C) return 0; long long t = (m > A[i] ? m - A[i] : 0); if (t == d[i]) break; if (!d[i]) --ret; d[i] = m = t; } return ret; } }; typedef Solution2 Solution; void testeach(long long c, const vector<long long> & a, const vector<long long> & b) { long long r1 = Solution1().solve(c, a, b); long long r2 = Solution().solve(c, a, b); if (r1 != r2){ print(a); print(b); cout << c << endl; cout << "Solution1: " << r1 << endl; cout << "Solution: " << r2 << endl; system("pause"); } } void test() { srand(time(0)); { vector<long long> a{ 3, 5, 5, 2, 5, 1, 4, 3 }; vector<long long> b{ 4, 1, 3, 5, 2, 2, 2, 3 }; long long k = 6; testeach(k, a, b); } { vector<long long> a{ 2, 3, 2, 4, 3, 4, 2, 2 }; vector<long long> b{ 4, 1, 5, 2, 1, 1, 5, 2 }; long long k = 8; testeach(k, a, b); } { vector<long long> a{ 2, 3, 4, 2, 4, 5, 2, 3 }; vector<long long> b{ 1, 3, 5, 3, 1, 1, 4, 2 }; long long k = 6; testeach(k, a, b); } { vector<long long> a{ 2, 5, 2, 3, 1, 1, 4, 2 }; vector<long long> b{ 2, 1, 1, 2, 3, 4, 2, 4 }; long long k = 7; testeach(k, a, b); } { vector<long long> a{ 3}; vector<long long> b{ 3 }; long long k = 2; testeach(k, a, b); } { vector<long long> a{ 3, 1, 2 }; vector<long long> b{ 2, 2, 2 }; long long k = 3; testeach(k, a, b); } for (; 1;){ vector<long long> a, b; genArray(a, 8, 1, 5); genArray(b, 8, 1, 5); int c = genRand(6, 10); testeach(c, a, b); } } int main() { //test(); return 0; int n; long long c; cin >> n >> c; vector<long long> a(n), b(n); for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) cin >> b[i]; cout << Solution().solve(c, a, b) << endl; }
#include <math.h> #include <RcppArmadillo.h> extern "C"{ void sadmvn_(int *n, double *lower, double *upper, int *infin, double *correl, int *maxpts, double *abseps, double *releps, double *error, double *value, int *inform ); }; // ordre parametres: // submod1, .., submodK, covRE, seuil1, gammas1, seuil2, gamma2 // avec prm submodl : nef+ncontr+nvc+ncor+ny+nalea+ntrtot // seuil : seuil, seuilX1, ..., seuilXnvarD // gammas : gamma1, gamma1X1, ..., gamma1XnvarD, ..., gammaK, gammaKX1, ..., gammaKXnvarD RcppExport SEXP loglikUACV(SEXP b0, SEXP bfix0, SEXP fix0, SEXP Y0, SEXP X0, SEXP Xd0, SEXP idD0, SEXP D0, SEXP Xseuil0, SEXP nmes0, SEXP nv0, SEXP idx0, SEXP idiag0, SEXP ncor0, SEXP ny0, SEXP nalea0, SEXP ntr0, SEXP link0, SEXP nodes0, SEXP epsY0, SEXP nRE0, SEXP nBM0, SEXP nbevt0, SEXP idcause0, SEXP entreRetard0, SEXP nbTronc0) { using namespace arma; Rcpp::NumericVector b00(b0); Rcpp::NumericVector bfix00(bfix0); Rcpp::IntegerVector fix00(fix0); Rcpp::NumericVector Y00(Y0); Rcpp::List X(X0); Rcpp::List Xd(Xd0); Rcpp::IntegerVector idD00(idD0); Rcpp::NumericMatrix D00(D0); Rcpp::IntegerMatrix nmes00(nmes0); Rcpp::IntegerVector nv00(nv0); Rcpp::IntegerMatrix idx00(idx0); Rcpp::IntegerVector idiag00(idiag0); Rcpp::IntegerVector ncor00(ncor0); Rcpp::IntegerVector ny00(ny0); Rcpp::IntegerVector nalea00(nalea0); Rcpp::IntegerVector ntr00(ntr0); Rcpp::IntegerVector link00(link0); Rcpp::NumericVector nodes00(nodes0); Rcpp::NumericVector epsY00(epsY0); int nRE = Rcpp::as<int>(nRE0); int nBM = Rcpp::as<int>(nBM0); Rcpp::NumericMatrix Xseuil00(Xseuil0); int nbevt = Rcpp::as<int>(nbevt0); Rcpp::IntegerVector idcause00(idcause0); Rcpp::IntegerVector entreRetard00(entreRetard0); Rcpp::IntegerMatrix nbTronc00(nbTronc0); int ns = nmes00.nrow(); int K = ny00.size(); int nvtot = idx00.ncol(); int nvarD = D00.ncol()-1; int ndept = idcause00.size()/nbevt - nvarD; int M = nmes00.ncol()-nbevt-1; vec b(b00.begin(),b00.size(),false); vec bfix(bfix00.begin(),bfix00.size()); ivec fix(fix00.begin(),fix00.size()); imat nmes(nmes00.begin(),ns,M+nbevt+1); ivec nv(nv00.begin(),nv00.size()); imat idx(idx00.begin(),4,nvtot); ivec idiag(idiag00.begin(),idiag00.size()); ivec ncor(ncor00.begin(),ncor00.size()); ivec ny(ny00.begin(),ny00.size()); ivec nalea(nalea00.begin(),nalea00.size()); vec Y(Y00.begin(),Y00.size()); ivec link(link00.begin(),link00.size()); vec nodes(nodes00.begin(),nodes00.size()); ivec ntr(ntr00.begin(),ntr00.size()); vec epsY(epsY00.begin(),epsY00.size()); mat D(D00.begin(),ns,nvarD+1); mat Xseuil(Xseuil00.begin(),Xseuil00.nrow(),Xseuil00.ncol()); ivec idcause(idcause00.begin(),idcause00.size()); ivec idD(idD00.begin(),idD00.size()); ivec entreRetard(entreRetard00.begin(),entreRetard00.size()); imat nbTronc(nbTronc00.begin(),ns,nbevt); int npm = b.size(); int npmfix = sum(fix); int npmtot = npm+npmfix; vec btot(npmtot); int i; int iest=0; int ifix=0; for(i=0; i<npmtot; i++) { if(fix(i)==0) { btot(i) = b(iest); iest += 1; } else { btot(i) = bfix(ifix); ifix += 1; } } // creer nef ncontr nea nvc ntrtot subnpm ivec nef(K); ivec ncontr(K); ivec nvarcontr(K); ivec nea(K); ivec nvc(K); ivec ntrtot(K); ivec subnpm(K); nef.fill(0); ncontr.fill(0); nvarcontr.fill(0); nea.fill(0); nvc.fill(0); ntrtot.fill(0); subnpm.fill(0); int j,k,l,p,q,ll,kk,m,endj,l0,m0,jexcl1,jexcl2; int jcurr,jdcurr,iidx,jseuil1curr,jseuil2curr,nmesdcurr,ncortotBM,npmMM; int nvarD1,nvarD2,ndept1,ndept2; int j1,j2,j3,kbm,kkbm,nu; int endj2,tmpntr,pcontr,ibeta,ibcontr,imatB,imatBM,ibtot,iRE,iBM,ispl,tmpcontr; int inodes,tmpnmes,ni,nik,ni0,ni01,ni02; double sig1,sig2,corr,yy,fct; double aatmp,bbtmp,aa,bb,cc,dd,jac; double ht,htm,ht2,ht3,h1,hh,h2,h3,h2n,hn,hht,mm,mm1,mm2,im,im1,im2,som; double vraistot,vrais_i,vrais_y,vrais_d; vec loglik; vec splaa,zitr,muK,muD,beta,bcontr,eta1,eta2,eta,eta1_dept,eta2_dept,eta_dept,varD; ivec nobs,nmescurr,nmescurry,niparK; mat gamma1,gamma2,B,U,BM,Ubm; vec Hyi,muiK,tcor,muiD,tdcor,yim,Hyim,ytemp1,ytemp3; mat RiK,Xi,Xcontri,Zi,RiD,Xdi,Zdi,RiKD,Xk,Xdk,VK,invVK; Rcpp::NumericVector ytemp2; int dimPhi,maxpts,inform,nTronc1,nTronc2; vec upper,lower,delta,seuil_i,upper1; ivec infin; uvec js; mat Gam1,GG,Gam2,Gam,tGam,GamTronc; mat VKD,VD,VD_K,V0,V1,I0,I1,ZCC,P,H; vec muiD_K,correl,un,h; double abseps,releps,error,value0,value1,valuer,retardi; std::vector<double> lower2,upper2,correl2,delta2; std::vector<int> infin2; rowvec g; loglik.zeros(2*ns); l0=0; m0=0; ncortotBM=0; for(k=0; k<K; k++) { nef(k) = -1; // pour ne pas compter l'intercept for(l=l0; l<l0+nv(k); l++) { if(idx(0,l)==1) { nef(k) += 1; } if(idx(1,l)==1) { nvarcontr(k) += 1; ncontr(k) += ny(k)-1; } if(idx(2,l)==1) { nea(k) += 1; } } if(idiag(k)==1) { nvc(k)=nea(k)-1; } else { nvc(k) = nea(k)*(nea(k)+1)/2-1; } for(m=m0; m<m0+ny(k); m++) { if(link(m)==0) { ntrtot(k) += 2; } if(link(m)==1) { ntrtot(k) += 4; } if(link(m)==2) { ntrtot(k) += ntr(m); } } if(ncor(k)==1) { ncortotBM += 1; } l0 += nv(k); m0 += ny(k); subnpm(k) = nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+ntrtot(k); } splaa.zeros(max(ntrtot)*K); npmMM = sum(subnpm); nobs = sum(nmes,0).t(); // nb d'obs por chaque Y // nvar par evt nvarD1 = 0; nvarD2 = 0; ndept1 = 0; ndept2 = 0; endj=(nvarD+ndept)*nbevt; for(j=0;j<endj;j++) { if(j<(nvarD+ndept)) //evt1 { if(idcause(j)==1) { if(j<nvarD) { nvarD1 += 1; } else { ndept1 += 1; } } } else //evt2 { if(idcause(j)==1) { if(j<(nvarD+ndept)+nvarD) { nvarD2 += 1; } else { ndept2 += 1; } } } } beta.zeros(sum(nef)+K); bcontr.zeros(sum(ncontr)+sum(nvarcontr)); eta1.zeros(nvarD1+1); eta2.zeros(nvarD2+1); eta.zeros(nbevt+nvarD1+nvarD2); eta1_dept.zeros(ndept1); eta2_dept.zeros(ndept2); eta_dept.zeros(ndept1+ndept2); gamma1.zeros(K,nvarD1+1); gamma2.zeros(K,nvarD2+1); varD.zeros(nvarD1+nvarD2+nbevt); B.zeros(sum(nea),sum(nea)); U.zeros(sum(nea),sum(nea)); BM.zeros(ncortotBM,ncortotBM); Ubm.zeros(ncortotBM,ncortotBM); ibeta=0; ibcontr=0; imatB=0; imatBM=0; ibtot=0; iRE=0; iBM=0; ispl=0; tmpcontr=0; // creer vecteurs beta (effets fixes des K MM) // vecteur eta (K seuils) // matrice B (mat par blocs, varcov des effets aleatoires des K MM) for(k=0; k<K; k++) { // effets fixes beta(ibeta) = 0; beta(span(ibeta+1,ibeta+nef(k))) = btot(span(ibtot,ibtot+nef(k)-1)); // contrastes for(l=0; l<nvarcontr(k); l++) { bcontr(span(ibcontr,ibcontr+ny(k)-2)) = btot(span(ibtot+nef(k)+tmpcontr,ibtot+nef(k)+tmpcontr+ny(k)-2)); bcontr(ibcontr+ny(k)-1) = -sum(btot(span(ibtot+nef(k)+tmpcontr,ibtot+nef(k)+tmpcontr+ny(k)-2))); tmpcontr += ny(k)-1; ibcontr += ny(k); } // varcov du sous-modele k U(imatB,imatB) = 1; // var(u0)=1 if(idiag(k)==1) { for(j=1; j<nea(k); j++) { U(imatB+j,imatB+j) = btot(ibtot+nef(k)+ncontr(k)+j-1); } } else { j=0; for(j2=0; j2<nea(k); j2++) { if(j2>0) { for(j1=0; j1<=j2; j1++) { U(imatB+j1,imatB+j2) = btot(ibtot+nef(k)+ncontr(k)+j); j += 1; } } if((imatB>0) & (nRE>0)) { for(j3=0; j3<sum(nea(span(0,k-1))); j3++) { U(j3,imatB+j2) = btot(npmMM+iRE); iRE +=1; } } } } // BM du sous-modele k if(ncor(k)==1) { Ubm(imatBM,imatBM) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)); if((imatBM>0) & (nBM>0)) { for(j3=0; j3<imatBM; j3++) { Ubm(j3,imatBM)=btot(npmMM+nRE+iBM); iBM += 1; } } imatBM += 1; } ibeta += nef(k)+1; ibtot += nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+ntrtot(k); imatB += nea(k); } // effets aleatoires endj2=U.n_cols; for(j2=0;j2<endj2;j2++) { sig2 = U(j2,j2); for(j1=0;j1<=j2;j1++) { if(j1==j2) { B(j1,j2)=sig2*sig2; //? ou exp(sig2)? } else { corr=(exp(U(j1,j2))-1)/(1+exp(U(j1,j2))); sig1 = U(j1,j1); B(j1,j2) = corr*fabs(sig1)*fabs(sig2); B(j2,j1)=B(j1,j2); } } } // BM endj2=Ubm.n_cols; for(j2=0;j2<endj2;j2++) { sig2 = Ubm(j2,j2); for(j1=0;j1<=j2;j1++) { if(j1==j2) { BM(j1,j2)=sig2*sig2; //? ou exp(sig2)? } else { corr=(exp(Ubm(j1,j2))-1)/(1+exp(Ubm(j1,j2))); sig1 = Ubm(j1,j1); BM(j1,j2) = corr*fabs(sig1)*fabs(sig2); BM(j2,j1)=BM(j1,j2); if(nBM>0) { btot(npmMM+nRE+iBM) = BM(j1,j2); iBM += 1; } } } } eta1 = btot(span(npmMM+nRE+nBM,npmMM+nRE+nBM+nvarD1)); eta(span(0,nvarD1)) = eta1; if(ndept1>0) { eta1_dept = btot(span(npmMM+nRE+nBM+1+nvarD1,npmMM+nRE+nBM+1+nvarD1+ndept1-1)); eta_dept(span(0,ndept1-1)) = eta1_dept; } if(nbevt==2) { eta2 = btot(span(npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1),npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1)+nvarD2)); if(ndept2>0) { eta2_dept = btot(span(npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1)+1+nvarD2,npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1)+1+nvarD2+ndept2-1)); eta_dept(span(ndept1,ndept1+ndept2-1)) = eta2_dept; } eta(span(nvarD1+1,nvarD1+nvarD2+1)) = eta2; } l=0; for(k=0;k<K;k++) { gamma1(k,span(0,nvarD1)) = trans(btot(span(npmMM+nRE+nBM+1+nvarD1+ndept1+l,npmMM+nRE+nBM+1+nvarD1+ndept1+l+nvarD1))); l += nvarD1+1; } if(nbevt==2) { l=0; for(k=0;k<K;k++) { gamma2(k,span(0,nvarD2)) = trans(btot(span(npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1)+1+nvarD2+ndept2+l,npmMM+nRE+nBM+1+nvarD1+ndept1+K*(1+nvarD1)+1+nvarD2+ndept2+l+nvarD2))); l += nvarD2+1; } } // nmescurr pour X // nmesdcurr pour Xd // nmescurry pour Y nmescurr=zeros<ivec>(K); nmescurry=zeros<ivec>(K); nmescurr(0)=0; nmescurry(0)=0; m0=0; if(K>1) { for(k=1; k<K; k++) { nmescurr(k) = 0; nmescurry(k) = sum(nobs(span(0,m0+ny(k-1)-1))); m0 += ny(k-1); } } // obs rangees par dimension, sujet, outcome puis temps nmesdcurr=0; jseuil1curr=0; jseuil2curr=nobs[M]; vraistot=0.0; vrais_i = 0.0; vrais_y = 0.0; vrais_d = 0.0; for(i=0; i<ns; i++) { vrais_i=0.0; ni01 = nmes(i,M); // nombre d'evaluation de la demence ni02=0; if(nbevt==2) ni02 = nmes(i,M+1); ni0 = nmes(i,M+nbevt); ni = sum(nmes.row(i))-ni0-ni01-ni02;// ni=sum(nikm) niparK.zeros(K); // vecteurs et matrices a ni lignes //? faire des maxmes plutot que de redefinir? Hyi.zeros(ni); muiK.zeros(ni); RiK.zeros(ni,ni); // contient cor, alpha et sigma Xi.zeros(ni,beta.size()); Xcontri.zeros(ni,bcontr.size()); Zi.zeros(ni,sum(nea)); tcor.zeros(ni); // vecteurs et matrices a ni0 lignes muiD.zeros(K*ni0); RiD.zeros(K*ni0,K*ni0);// contient cor Xdi.zeros(K*ni0,beta.size()); Zdi.zeros(K*ni0,B.n_cols); tdcor.zeros(K*ni0); RiKD.zeros(RiK.n_rows,RiD.n_cols);// contient cor inodes=0; ibtot=0; jcurr=0; jdcurr=0; iidx=0; p=0; pcontr=0; q=0; jac=0; ispl=0; m0=0; kbm=0; // remplir les vecteurs et matrices outcome par outcome for(k=0; k<K; k++) { nik = sum(nmes(i,span(m0,m0+ny(k)-1))); tmpnmes=0; tmpntr=0; //transfos for(m=m0; m<m0+ny(k); m++) { if(nmes(i,m)==0) continue; // !ne devrait pas arriver, gerer dans R! niparK(k) += nmes(i,m); // construire H(Y) et calculer le jacobien yim = Y(span(nmescurry(k)+tmpnmes,nmescurry(k)+tmpnmes+nmes(i,m)-1)); Hyim.zeros(nmes(i,m)); if(link(m)==0) { Hyim = (yim - btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr)) / btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+1); jac += -nmes(i,m)*log(btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+1)); tmpntr += 2; inodes += 2; } else { if(link(m)==1) { aatmp = exp(btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr)) / (1+exp(btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr))); bbtmp = exp(btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+1)) / (1+exp(btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+1))); bbtmp = aatmp*(1-aatmp)*bbtmp; cc = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+2); cc = fabs(cc); dd = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+3); dd = fabs(dd); aa = aatmp*aatmp*(1-aatmp)/bbtmp-aatmp; bb = aa*(1-aatmp)/aatmp; ytemp1.zeros(yim.size()); ytemp1 = (yim-nodes(inodes)+epsY(m)) / (nodes(inodes+1)-nodes(inodes)+2*epsY(m)); ytemp2 = Rcpp::as<Rcpp::NumericVector>(Rcpp::wrap(ytemp1)); Hyim=Rcpp::pbeta(ytemp2,aa,bb); ytemp3 = Rcpp::dbeta(ytemp2,aa,bb); endj2=yim.size(); for(j2=0;j2<endj2;j2++) { yy = ytemp3(j2);//Rcpp::dbeta(ytemp2(j2),aa,bb); jac += std::log(std::abs(yy)/dd); ll = std::abs(nodes(inodes+1)-nodes(inodes)+2*epsY(m)); jac -= std::log(ll); } tmpntr += 4; inodes += 2; } else { if(link(m)==2) { /// prm splines dans splaa splaa.zeros(ntr(m)); splaa(0) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr); for(kk=1; kk<ntr(m); kk++) { splaa(kk) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+kk)*btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+tmpntr+kk); } // repeter les noeuds dans zitr zitr.zeros(ntr(m)+2); zitr(0)=nodes(inodes); zitr(1)=zitr(0); zitr(span(2,ntr(m)-1))=nodes(span(inodes,inodes+ntr(m)-3)); zitr(ntr(m))=zitr(ntr(m)-1); zitr(ntr(m)+1)=zitr(ntr(m)-1); // calcul de H(y) for(j=0;j<nmes(i,m);j++) { ll=0; if(yim(j)==nodes(inodes+ntr(m)-3)) { ll=ntr(m)-2; } som=0.0; for(kk=3;kk<ntr(m);kk++) { if((yim(j)>=zitr(kk-1)) && (yim(j)<zitr(kk))) { ll=kk-1; } } if((ll<2) || (ll>ntr(m)-2)) { vraistot=-1E9; goto fin; } som=splaa(0); if(ll>2) { som=som+sum(splaa(span(1,ll-2))); } ht2 = zitr(ll+1)-yim(j); htm= yim(j)-zitr(ll-1); ht = yim(j)-zitr(ll); ht3 = zitr(ll+2)-yim(j); hht = yim(j)-zitr(ll-2); h1 = zitr(ll+1)-zitr(ll); hh= zitr(ll+1)-zitr(ll-1); hn= zitr(ll+1)-zitr(ll-2); h2n=zitr(ll+2)-zitr(ll-1); h2= zitr(ll+2)-zitr(ll); h3= zitr(ll+3)-zitr(ll); if(yim(j)==zitr(ntr(m)-1)) { mm2=0.0; mm1=0.0; mm=3.0/h1; } else { mm2=(3.0*ht2*ht2)/(hh*h1*hn); mm1=(3.0*htm*ht2)/(h2n*hh*h1)+(3.0*ht*ht3)/(h2*h1*h2n); mm=(3.0*ht*ht)/(h3*h2*h1); } if((mm<0) || (mm1<0) || (mm2<0)) { vraistot=-1E9; goto fin; } im2 = hht*mm2/(3.0) + h2n*mm1/(3.0) + h3*mm/(3.0); im1 = htm*mm1/(3.0) + h3*mm/(3.0); im = ht*mm/(3.0); Hyim(j) = som + splaa(ll-1)*im2 + splaa(ll)*im1 + splaa(ll+1)*im; jac += log(splaa(ll-1)*mm2+splaa(ll)*mm1+splaa(ll+1)*mm); } inodes += ntr(m)-2; tmpntr += ntr(m); } } } Hyi(span(jcurr+tmpnmes,jcurr+tmpnmes+nmes(i,m)-1)) = Hyim; tmpnmes += nmes(i,m); }// fin boucle m // toutes les variables du k-ieme MM sont dans l'element k de la liste X Xk = Rcpp::as<arma::mat>(X[k]); Xdk = Rcpp::as<arma::mat>(Xd[k]); for(l=0; l<nv(k); l++) { if(idx(0,iidx+l)==1) // effet fixe { //cout << "p=" << p << " l=" << l << endl; Xi(span(jcurr,jcurr+nik-1),p) = Xk(span(nmescurr(k),nmescurr(k)+nik-1),l); Xdi(span(jdcurr,jdcurr+ni0-1),p) = Xdk(span(nmesdcurr,nmesdcurr+ni0-1),l); p += 1; } if(idx(1,iidx+l)==1) // contraste { tmpnmes=0; ll=0; for(m=m0; m<m0+ny(k); m++) { Xcontri(span(jcurr+tmpnmes,jcurr+tmpnmes+nmes(i,m)-1),ny(k)*pcontr+ll) = Xk(span(nmescurr(k)+tmpnmes,nmescurr(k)+tmpnmes+nmes(i,m)-1),l); ll += 1; tmpnmes += nmes(i,m); } pcontr += 1; } if(idx(2,iidx+l)==1) // effet aleatoire { Zi(span(jcurr,jcurr+nik-1),q) = Xk(span(nmescurr(k),nmescurr(k)+nik-1),l); Zdi(span(jdcurr,jdcurr+ni0-1),q) = Xdk(span(nmesdcurr,nmesdcurr+ni0-1),l); q += 1; } if(idx(3,iidx+l)==1) // temps pour BM ou AR { tcor(span(jcurr,jcurr+nik-1)) = Xk(span(nmescurr(k),nmescurr(k)+nik-1),l); tdcor(span(jdcurr,jdcurr+ni0-1)) = Xdk(span(nmesdcurr,nmesdcurr+ni0-1),l); } } iidx += nv(k); // construire Rk, Rd et Rkd (correlations BM ou AR ) if(ncor(k)>0) { if(ncor(k)==1) // BM { for(j1=0; j1<nik; j1++) { for(j2=0; j2<nik; j2++) { RiK(jcurr+j1,jcurr+j2) = BM(kbm,kbm)* std::min(tcor(jcurr+j1),tcor(jcurr+j2)); } for(j3=0; j3<ni0; j3++) { RiKD(jcurr+j1,jdcurr+j3) = BM(kbm,kbm)* std::min(tcor(jcurr+j1),tdcor(jdcurr+j3)); } } for(j1=0; j1<ni0; j1++) { for(j2=0; j2<ni0; j2++) { RiD(jdcurr+j1,jdcurr+j2) = BM(kbm,kbm)* std::min(tdcor(jdcurr+j1),tdcor(jdcurr+j2)); } } // correlation des BM : a refaire if((kbm>0) & (nBM>0)) { kk=0; tmpnmes=0; kkbm=0; // dans Rik et Rikd: for(j1=0; j1<jcurr; j1++) { if(j1==tmpnmes+niparK(kk)) { tmpnmes += niparK(kk); kk += 1; if(ncor(kk)==1) kkbm += 1; } for(j2=jcurr; j2<jcurr+nik; j2++) { RiK(j1,j2) = BM(kkbm,kbm)*std::min(tcor(j1),tcor(j2)); } for(j3=jdcurr; j3<jdcurr+ni0; j3++) { RiKD(j1,j3) = BM(kkbm,kbm)*std::min(tcor(j1),tdcor(j3)); } } kk=0; tmpnmes=0; kkbm=0; // dans RiD: for(j1=0; j1<jdcurr; j1++) { if(j1==tmpnmes+ni0) { tmpnmes += ni0; kk += 1; if(ncor(kk)==1) kkbm += 1; } // cov entre 2 BM tdem for(j3=jdcurr; j3<jdcurr+ni0; j3++) { RiD(j1,j3) = BM(kkbm,kbm)*std::min(tdcor(j1),tdcor(j3)); } } } kbm += 1; } else // AR { for(j1=0; j1<nik; j1++) { for(j2=0; j2<nik; j2++) { RiK(jcurr+j1,jcurr+j2) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* exp(-btot(ibtot+nef(k)+ncontr(k)+nvc(k))* fabs(tcor(jcurr+j1)-tcor(jcurr+j2))); } for(j3=0; j3<ni0; j3++) { RiKD(jcurr+j1,jdcurr+j3) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* exp(-btot(ibtot+nef(k)+ncontr(k)+nvc(k))* fabs(tcor(jcurr+j1)-tdcor(jdcurr+j3))); } } for(j1=0; j1<ni0; j1++) { for(j2=0; j2<ni0; j2++) { RiD(jdcurr+j1,jdcurr+j2) = btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* btot(ibtot+nef(k)+ncontr(k)+nvc(k)+1)* exp(-btot(ibtot+nef(k)+ncontr(k)+nvc(k))* fabs(tdcor(jdcurr+j1)-tdcor(jdcurr+j2))); } } } // fin AR } // fin ncor // alpha (intercept aleatoire specif au marqueur) if(nalea(k)>0) { ll=0; tmpnmes=0; for(m=m0; m<m0+ny(k); m++) { for(j1=0; j1<nmes(i,m); j1++) { for(j2=0; j2<nmes(i,m); j2++) { RiK(jcurr+tmpnmes+j1,jcurr+tmpnmes+j2) += btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+ll)* btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+ll); } } tmpnmes += nmes(i,m); ll += 1; } } // erreur de mesure ll=0; tmpnmes=0; for(m=m0; m<m0+ny(k); m++) { for(j1=0; j1<nmes(i,m); j1++) { RiK(jcurr+tmpnmes+j1,jcurr+tmpnmes+j1) += btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ll)* btot(ibtot+nef(k)+ncontr(k)+nvc(k)+ncor(k)+ll); } tmpnmes += nmes(i,m); ll += 1; } nmescurr(k) += nik; jcurr += nik; ibtot += nef(k)+ncontr(k)+nvc(k)+ncor(k)+ny(k)+nalea(k)+ntrtot(k); nmescurry(k) += nik; jdcurr += ni0; m0 += ny(k); } // fin boucle k // definir les quantites qui interviennent dans f(y) muiK = Xi*beta + Xcontri*bcontr; VK = Zi*B*trans(Zi) + RiK ; //valea+sigma contenu dans Rik aa = det(VK); if(aa<1.0E-10) { cout << "det(VK)=" << det(VK) << endl; vraistot=-1E9; goto fin; } invVK = inv_sympd(VK); // calcul de f(y) en log vraistot += as_scalar( -ni*log(2*datum::pi) -log(det(VK)) - trans(Hyi-muiK)*invVK*(Hyi-muiK))/2 + jac; vrais_i = as_scalar( -ni*log(2*datum::pi) -log(det(VK)) - trans(Hyi-muiK)*invVK*(Hyi-muiK))/2 + jac; //if(i<10) cout << "vrais_i=" << vrais_i << endl; vrais_y += as_scalar( -ni*log(2*datum::pi) -log(det(VK)) - trans(Hyi-muiK)*invVK*(Hyi-muiK))/2 + jac; // debut evts // vrais_d = 0.0; // definir les quantites qui interviennent dans Phi(K*ni0) dimPhi = ni01+ni02; upper.zeros(dimPhi); lower.zeros(dimPhi); delta.zeros(dimPhi); nu=0; infin.zeros(dimPhi); varD.fill(0); // variables explicatives non dep du tps sur D varD(0) = 1.0; if(nbevt==2) varD(nvarD1+1) = 1.0; if(nvarD>0) { l=1; for(j=0;j<nvarD;j++) { if(idcause(j)==1) { varD(l) = D(i,j+1); l += 1; } } if(nbevt==2) { l+=1; // car intercept de D2 (en place nvarD1+1) deja rempli for(j=0;j<nvarD;j++) { if(idcause(nvarD+ndept+j)==1) { varD(l) = D(i,j+1); l += 1; } } } } Gam1.zeros(ni01,K*ni0); // contribution des dimension sur Dem GG.zeros(ni01,ni0); l=0; for(j=0;j<ni0;j++) { if(idD(nmesdcurr+j)==1) { GG(l,j)=1; l+=1; } } Gam1 = kron(trans(gamma1*varD(span(0,nvarD1))),GG); Gam2.zeros(ni02,K*ni0); // contribution des dimension sur Dc if(nbevt==2) { GG.zeros(ni02,ni0); l=0; for(j=0;j<ni0;j++) { if(idD(nobs[M+2]+nmesdcurr+j)==1) { GG(l,j)=1; l+=1; } } Gam2 = kron(trans(gamma2*varD(span(nvarD1+1,nvarD1+1+nvarD2))),GG); } Gam = join_vert(Gam1,Gam2); tGam=trans(Gam); seuil_i.ones(ni01+ni02); // seuil a chaque temps seuil_i(span(0,ni01-1)) *= dot(eta1,varD(span(0,nvarD1))); if(nbevt==2) seuil_i(span(ni01,ni01+ni02-1)) *= dot(eta2,varD(span(nvarD1+1,nvarD1+nvarD2+1))); if(ndept>0) { if(ndept1>0) { for(j=0; j<ni01; j++) { seuil_i(j) += dot(eta1_dept,trans(Xseuil(jseuil1curr+j,span(0,ndept1-1)))); } } if(ndept2>0) { for(j=0; j<ni02; j++) { seuil_i(ni01+j) += dot(eta2_dept,trans(Xseuil(jseuil2curr+j,span(ndept1,ndept1+ndept2-1)))); } } } // on conditionne sur Lambda pour calculer la vrais // muiD = Xdi*beta; //moyenne de Lambda VKD = Zi*B*trans(Zdi) + RiKD; //covariance de Y et Lambda VD = Zdi*B*trans(Zdi) + RiD; //variance de Lambda muiD_K = muiD + trans(VKD)*invVK*(Hyi-muiK); // moyenne de Lambda sachant Y VD_K = VD-trans(VKD)*invVK*VKD; // variance de Lambda sachant Y upper = seuil_i - Gam*muiD_K; // borne de l'integration pour Phi V0.zeros(ni01+ni02,ni01+ni02); I0.eye(ni01+ni02,ni01+ni02); V0 = I0 + Gam*VD_K*tGam; // variance de Phi lower = upper; maxpts = 10000*dimPhi; abseps = 0.001; releps = 0.0001; error =0; value0 = 0; inform = 0; // creation du vecteur des correlations a partir de V0 correl.zeros((ni01+ni02)*(ni01+ni02+1)/2-ni01-ni02); endj2 = ni01+ni02; dimPhi = ni01+ni02; jexcl1 = -1; jexcl2 = -1; if(nbTronc(i,0)>0) { jexcl1 = 0; dimPhi -= 1; } if(nbevt==2) { if(nbTronc(i,1)>0) { jexcl2 = ni01; dimPhi -= 1; } } upper1.zeros(dimPhi); kk=0; ll=0; for(j2=0; j2<endj2; j2++) { if(j2==jexcl2) continue; if(j2!=jexcl1) { upper1(kk) = upper(j2)/pow(V0(j2,j2),0.5); kk += 1; } if(j2>0) { for(j1=0; j1<j2; j1++) { if(j1==jexcl1) continue; correl(ll) = V0(j1,j2)/(pow(V0(j1,j1),0.5)*pow(V0(j2,j2),0.5)); ll += 1; } } } lower2 = conv_to< std::vector<double> >::from(lower); upper2 = conv_to< std::vector<double> >::from(upper1); infin2 = conv_to< std::vector<int> >::from(infin); correl2 = conv_to< std::vector<double> >::from(correl); delta2 = conv_to< std::vector<double> >::from(delta); // calcul de Phi(K*ni0) sadmvn_(&dimPhi,&lower2[0],&upper2[0],&infin[0],&correl2[0],&maxpts,&abseps,&releps,&error,&value0,&inform); if(inform!=0) { cout << "probleme integration 0 :" << "value=" << value0 << " error=" << error << endl; vraistot=-1E9; goto fin; } if(D(i,0)==0) { vrais_d += log(value0); vraistot += log(value0); } //Phi(K*(ni0-1)) calcule dans le cas Dem if(D(i,0)==1) { dimPhi -= 1; if(dimPhi>0) { maxpts=10000*dimPhi; // matrice pr enlever la ligne correspondant au tps de Dem P = join_vert(join_horiz(eye<mat>(ni01-1,ni01-1), zeros<mat>(ni01-1,ni02+1)), join_horiz(zeros<mat>(ni02,ni01),eye<mat>(ni02,ni02))); un.ones(ni0-1); upper = P*(seuil_i - Gam*muiD_K); I1.eye(ni01+ni02-1,ni01+ni02-1); V1.zeros(ni01+ni02-1,ni01+ni02-1); V1 = I1 + P*Gam*VD_K*tGam*trans(P); //correlations jexcl2 -= 1; correl.zeros(); endj2 = V1.n_cols; upper1.zeros(dimPhi); kk=0; ll=0; for(j2=0; j2<endj2; j2++) { if(j2==jexcl2) continue; if(j2!=jexcl1) { upper1(kk) = upper(j2)/pow(V1(j2,j2),0.5); kk += 1; } if(j2>0) { for(j1=0; j1<j2; j1++) { if(j1==jexcl1) continue; correl(ll) = V1(j1,j2)/(pow(V1(j1,j1),0.5)*pow(V1(j2,j2),0.5)); ll += 1; } } } upper2 = conv_to< std::vector<double> >::from(upper1); correl2 = conv_to< std::vector<double> >::from(correl); value1 = 0; // calcul de Phi Dem sadmvn_(&dimPhi,&lower2[0],&upper2[0],&infin[0],&correl2[0],&maxpts,&abseps,&releps,&error,&value1,&inform); if(inform!=0) { cout << "probleme integration 1 :" << inform << " error=" << error << endl; vraistot=-1E9; goto fin; } } else { value1 = 1; } vrais_d += log(value1-value0); vraistot += log(value1-value0); } // cas Dc if(D(i,0)==2) { dimPhi -= 1; if(dimPhi>0) { maxpts=10000*dimPhi; // matrice pr enlever la ligne correspondant au tps de Dc P = join_horiz(eye<mat>(ni01+ni02-1,ni01+ni02-1),zeros<vec>(ni01+ni02-1)); upper = P*(seuil_i - Gam*muiD_K); V1.zeros(ni01+ni02-1,ni01+ni02-1); I1.eye(ni01+ni02-1,ni01+ni02-1); V1 = I1 + P*Gam*VD_K*tGam*trans(P); correl.zeros(); endj2 = V1.n_cols; upper1.zeros(dimPhi); kk=0; ll=0; for(j2=0; j2<endj2; j2++) { if(j2==jexcl2) continue; if(j2!=jexcl1) { upper1(kk) = upper(j2)/pow(V1(j2,j2),0.5); kk += 1; } if(j2>0) { for(j1=0; j1<j2; j1++) { if(j1==jexcl1) continue; correl(ll) = V1(j1,j2)/(pow(V1(j1,j1),0.5)*pow(V1(j2,j2),0.5)); ll += 1; } } } upper2 = conv_to< std::vector<double> >::from(upper1); correl2 = conv_to< std::vector<double> >::from(correl); value1 = 0; sadmvn_(&dimPhi,&lower2[0],&upper2[0],&infin[0],&correl2[0],&maxpts,&abseps,&releps,&error,&value1,&inform); if(inform!=0) { cout << "probleme integration 2 :" << inform << " error=" << error << endl; vraistot=-1E9; goto fin; } vrais_d += log(value1-value0); vraistot += log(value1-value0); } else { // si 1 seule mesure de D value1 = 1; vrais_d += log(value1-value0); vraistot += log(value1-value0); } } loglik(i) = vrais_d; // entree retardee if(any(entreRetard==1)) { retardi = 0.0; if(nbevt==1) { dimPhi=nbTronc(i,0); upper.zeros(nbevt); V0.zeros(nbevt,nbevt); upper = seuil_i(0) - Gam1.row(0)*muiD; V0 = eye<mat>(nbevt,nbevt) + Gam1.row(0) * ( Zdi*B*trans(Zdi) + RiD ) * trans(Gam1.row(0)); upper(0) = upper(0)/pow(V0(0,0),0.5); correl.zeros(); } else { // 2 evts nTronc1 = nbTronc(i,0); nTronc2 = nbTronc(i,1); dimPhi = nTronc1+nTronc2; js.zeros(dimPhi); GamTronc.zeros(dimPhi,K*ni0); if((nTronc1>0) & (nTronc2>0)) { GamTronc = join_vert(Gam1.row(0), Gam2.row(0)); } else { if(nTronc1>0) GamTronc = Gam1.row(0); if(nTronc2>0) GamTronc = Gam2.row(0); } if(nTronc1>0) js(0) = 0; if(nTronc2>0) js(nTronc1) = ni01; upper.zeros(dimPhi); V0.zeros(dimPhi,dimPhi); if(dimPhi>0) { upper = seuil_i(js) - GamTronc*muiD; V0 = eye<mat>(dimPhi,dimPhi) + GamTronc * ( Zdi*B*trans(Zdi) + RiD ) * trans(GamTronc); correl.zeros(); endj2 = V0.n_cols; for(j2=0; j2<endj2; j2++) { if(j2>0) { for(j1=0; j1<j2; j1++) { correl(j1+((j2-1)*j2)/2) = V0(j1,j2)/(pow(V0(j1,j1),0.5)*pow(V0(j2,j2),0.5)); } } upper(j2) = upper(j2)/pow(V0(j2,j2),0.5); } } } lower=upper; upper2 = conv_to< std::vector<double> >::from(upper); lower2 = conv_to< std::vector<double> >::from(lower); correl2 = conv_to< std::vector<double> >::from(correl); if(dimPhi>0) { sadmvn_(&dimPhi,&lower2[0],&upper2[0],&infin[0],&correl2[0],&maxpts,&abseps,&releps,&error,&retardi,&inform); if(inform!=0) { cout << "probleme integration retard :" << inform << " error=" << error << endl; vraistot=-1E9; goto fin; } vraistot -= log(retardi); loglik(i) -= log(retardi); } } // fin entree retardee loglik(ns+i) = loglik(i) + vrais_i; jseuil1curr += ni01; jseuil2curr += ni02; nmesdcurr += ni0; } // fin boucle i fin: return Rcpp::wrap(loglik); }
#include <stdio.h> int MSS(int[], int); int MSS1(int[], int); int MSS2(int[], int); int MaxSubseqSum3(int[], int); int main() { freopen("in.txt", "r", stdin); int n; int a[100000]; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", a+i); } printf("%d", MSS(a, n)); return 0; } int MSS(int seq[], int n) { int thisSum=0, maxSum=0; for (int i = 0; i < n; i++) { thisSum += seq[i]; if (thisSum > maxSum) { maxSum = thisSum; } else if (thisSum < 0) { thisSum = 0; } } return maxSum; } int MSS1(int seq[], int n) { int maxSum = 0; int i,j,k,thisSum; for (i = 0; i < n; i++) { for (j = i;j < n; j++) { thisSum = 0; for (k = i; k < j; k++) { thisSum += seq[k]; } if (thisSum > maxSum) { maxSum = thisSum; } } } return maxSum; } int MSS2(int seq[], int n) { int maxSum = 0; int i,j,k,thisSum; for (i = 0; i < n; i++) { thisSum = 0; for (j = i;j < n; j++) { thisSum += seq[j]; if (thisSum > maxSum) { maxSum = thisSum; } } } return maxSum; } int Max3( int A, int B, int C ) { /* 返回3个整数中的最大值 */ // return A > B ? A > C ? A : C : B > C ? B : C; A < B ? A = B:0; A < C ? A = C:0; return A; } int DivideAndConquer( int List[], int left, int right ) { /* 分治法求List[left]到List[right]的最大子列和 */ int MaxLeftSum, MaxRightSum; /* 存放左右子问题的解 */ int MaxLeftBorderSum, MaxRightBorderSum; /*存放跨分界线的结果*/ int LeftBorderSum, RightBorderSum; int center, i; if( left == right ) { /* 递归的终止条件,子列只有1个数字 */ if( List[left] > 0 ) return List[left]; else return 0; } /* 下面是"分"的过程 */ center = ( left + right ) / 2; /* 找到中分点 */ /* 递归求得两边子列的最大和 */ MaxLeftSum = DivideAndConquer( List, left, center ); MaxRightSum = DivideAndConquer( List, center+1, right ); /* 下面求跨分界线的最大子列和 */ MaxLeftBorderSum = 0; LeftBorderSum = 0; for( i=center; i>=left; i-- ) { /* 从中线向左扫描 */ LeftBorderSum += List[i]; if( LeftBorderSum > MaxLeftBorderSum ) MaxLeftBorderSum = LeftBorderSum; } /* 左边扫描结束 */ MaxRightBorderSum = 0; RightBorderSum = 0; for( i=center+1; i<=right; i++ ) { /* 从中线向右扫描 */ RightBorderSum += List[i]; if( RightBorderSum > MaxRightBorderSum ) MaxRightBorderSum = RightBorderSum; } /* 右边扫描结束 */ /* 下面返回"治"的结果 */ return Max3( MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum ); } int MaxSubseqSum3( int List[], int N ) { /* 保持与前2种算法相同的函数接口 */ return DivideAndConquer( List, 0, N-1 ); }
#include "LayerGameOver.h" #include "AppMacros.h" #include "LayerGameMain.h" #include "Plane.h" CCScene * LayerGameOver::scene() { CCScene * scene = CCScene::create(); LayerGameOver * layer = LayerGameOver::create(); scene->addChild(layer); return scene; } bool LayerGameOver::init() { CCLayer::init(); CCSprite * background = CCSprite::createWithSpriteFrameName("gameover.png"); background->setAnchorPoint(ccp(0, 0)); background->setPosition(ccp(0, 0)); const char *scoreStr = CCString::createWithFormat("%d", LayerGameMain::score)->getCString(); CCLabelBMFont *finalScore = CCLabelBMFont::create(scoreStr, "font/font.fnt"); finalScore->setColor(ccc3(143, 146, 147)); //finalScore->setAnchorPoint(ccp(0.5, 1)); finalScore->setPosition(ccp(winSize.width / 2, winSize.height / 2 + 50)); CCSprite * nor = CCSprite::createWithSpriteFrameName("btn_finish.png"); CCSprite * press = CCSprite::createWithSpriteFrameName("btn_finish.png"); //! 重新开始按钮 CCMenuItemSprite *overItem = CCMenuItemSprite::create(nor, press, this, menu_selector(LayerGameOver::restartGameMCallBack)); //! 放在中间偏下 overItem->setPosition(ccp(winSize.width / 2, winSize.height / 2 - 50)); CCMenu *pauseMenu = CCMenu::create(overItem, NULL); pauseMenu->setPosition(CCPointZero); addChild(background); addChild(finalScore); addChild(pauseMenu); return true; } void LayerGameOver::restartGameMCallBack(CCObject* obj) { LayerGameMain::score = 0; Plane::_splane = NULL; CCScene *pscene = LayerGameMain::scene(); CCDirector::sharedDirector()->replaceScene(pscene); }
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <cstring> #include<iomanip> #include<string> #include<cmath> #include "Header.h" using namespace std; const int MAX = 30; const char Tmp_fileName[] = "buff.txt"; //name of a buffer-file which is used to convert a double number //to a char* int edit(fstream&, const char fileName[], int k, Grid* cells); int print(fstream&, const char fileName[], int k, Grid* cells); int save(fstream&, const char fileName[], int k, Grid* cells); int save_as(fstream&, const char fileName[], int k, Grid* cells); int quit(fstream&, const char fileName[], int k, Grid* cells); struct command { char key; const char * name; int(*function)(fstream&, const char file_name[], int k, Grid* cells); // a pointer to a command function ; } commands[] = { { 'e', "Edit", edit }, { 'p', "Print", print }, { 's', "Save", save }, { 'a', "Save as", save_as }, { 'q', "Quit", quit }, { 0, NULL, NULL } }; int space(Grid* cells, int k, int column) //a help function which makes the grid even { //it returns the max length of the column int j=0; for (int i = 0; i < k; i++) { if (j < strlen(cells[i].getContent()) && cells[i].getColumn() == column) j = strlen(cells[i].getContent()); } return j; } int maxCol(fstream& file) // a function which commas how many commas { //are found and returns the number of commas char ch; // of the line with maximum commas int max = 0; int comma = 0; file.clear(); file.seekg(0, file.beg); while (file) { ch = file.get(); if (ch == '\n') comma = 0; if (ch == ',') comma++; if (comma > max) max = comma; if (ch == '\\') ch = file.get(); } return max; } double calculator(double number1, double number2, char operation) // calculator which { // performs the basic operations switch (operation) { case '+':return number1 + number2; break; case '-':return number1 - number2; break; case '/':return number1 / number2; break; case '*':return number1 * number2; break; case '^':return pow(number1, number2); break; default: cout << "Invalid operation" << endl; } return 0; } char* convertTochar(double n, Grid cell) // a function which convert a double/int number { // to a string ofstream otmp(Tmp_fileName); otmp << n; otmp.close(); ifstream itmp(Tmp_fileName, ios::in); itmp.seekg(0, itmp.end); int length = itmp.tellg(); itmp.seekg(0, itmp.beg); char * buffer = new char[length+1]; int a = 0; char ch; while (itmp) { ch = itmp.get(); buffer[a] = ch; a++; } buffer[--a] = {'\0'}; itmp.close(); _unlink(Tmp_fileName); return buffer; } void calculateCells(Grid* cells, int k) //function which check if a cell contains formula { //and if so, calculates it int b = 0; double number, number2, number1; int column, row; bool first = true; char operation = 'o'; for (int i = 0; i < k; i++) { if (cells[i].getContent()[0] == '=') { first = true; for (int j = 1; j < strlen(cells[i].getContent()); j++) { if (cells[i].getContent()[j] == 'R') { j++; } char* buff = new char[strlen(cells[i].getContent()) + 1]; while (cells[i].getContent()[j] >= '0' && cells[i].getContent()[j] <= '9' || cells[i].getContent()[j] == '.') { buff[b] = cells[i].getContent()[j]; b++; j++; } buff[b] = { '\0' }; if (cells[i].getContent()[j] == 'C') { row = atoi(buff); j++; b = 0; while (cells[i].getContent()[j] >= '0' && cells[i].getContent()[j] <= '9') { buff[b] = cells[i].getContent()[j]; b++; j++; } buff[b] = { '\0' }; column = atoi(buff); int t = 0; while (t < k && (cells[t].getRow() != row || cells[t].getColumn() != column)) { t++; } if (cells[t].getRow() != row || cells[t].getColumn() != column || cells[t].checkStr(cells[t])==false) number = 0; else number = atof(cells[t].getContent()); if (first) { number1 = number; first = false; operation = cells[i].getContent()[j]; } else number2 = number; } else { if (first) { number1 = atof(buff); first = false; operation = cells[i].getContent()[j]; } else { number2 = atof(buff); } } b = 0; delete[] buff; } if (operation == '/' && number2 == 0) cells[i].setContent("ERROR"); else { double n = calculator(number1, number2, operation); if (n == 0) n = 0; cells[i].setContent(convertTochar(n, cells[i])); } } } } int edit(fstream& file, const char fileName[], int k, Grid* cells) //edit command { int row, column; cout << "Row:"; do { cin >> row; if (row > k / (maxCol(file) + 1)) cout<<"Please, enter a number, which is not bigger than " << k / (maxCol(file) + 1) << endl; } while (row > k / (maxCol(file) + 1)); cout << "Column:"; do { cin >> column; if(column>maxCol(file)+1) cout<<"Please, enter a number, which is not bigger than " <<(maxCol(file) + 1) << endl; } while (column > maxCol(file) + 1); for (int i = 0; i < k; i++) { if (cells[i].getRow() == row && cells[i].getColumn() == column) { int j = strlen(cells[i].getContent()); cout << "Content:"; char* content = new char[j]; cin >> content; cells[i].setContent(content); } } calculateCells(cells, k); return 0; } int save(fstream& file, const char fileName[], int k, Grid* cells) //save command { int columns= maxCol(file)+1; ofstream output(fileName); for (int i = 0; i < k; i++) { output << cells[i].getContent(); if (cells[i].getColumn() != columns) output << ","; else output << endl; } file.clear(); file.seekg(0); output.close(); cout<<fileName << " successfully saved! " << endl; return 0; } int save_as(fstream& file, const char fileName[], int k, Grid* cells) //save as command { char path[50]; ofstream output; bool exist = 1; int columns = maxCol(file) + 1; do { cin >> path; ofstream output(path); if (!output) { cout << "The directory has not been found!" << endl << "Please enter another directory!" << endl; exist = 0; } else exist = 1; } while(!exist); output.open(path); for (int i = 0; i < k; i++) { output << cells[i].getContent(); if (cells[i].getColumn() != columns) output << ","; else output << endl; } file.clear(); file.seekg(0); output.close(); cout << "Successfully saved to "<<path<< endl; return 0; } int print(fstream& file, const char fileName[], int k, Grid* cells) //print command { for (int i = 0; i < k; i++) { int column = cells[i].getColumn(); if (column == 1 && i != 0) cout << endl; cout << " "; int dist = space(cells, k, column); cout << setw(dist + 1) << setiosflags(ios::left) << cells[i].getContent(); cout<< "|"; } cout << endl; return 0; } int quit(fstream& file, const char file_name[], int k, Grid* cells) //command for quitting { file.close(); cout << "Exiting the program ..." << endl; return 1; } void print_menu() // start menu { cout << "MENU" << endl; for (int i = 0; commands[i].name; ++i) { cout << commands[i].key << " : " << commands[i].name << "\n"; } } int read_command() { char key = -1; cin >> key; if (!cin) return 1; for (int i = 0; commands[i].name; ++i) //loop which compares the possible { // commands and the command entered by the user if (commands[i].key == key) //and returns the index of the command return i; } cout << "Command cannot be executed" << endl; return -1; } int execute_command(int command, fstream& file, const char file_name[], int k, Grid* cells) { if (command >= 0 && commands[command].function) { return commands[command].function(file, file_name, k, cells); // brings the execution of a command } return 0; } void start(fstream& file, char fileName[MAX]) //inititialization of the file { cout << "File name: "; cin.getline(fileName, MAX); file.open(fileName); if (!file) { cout << "The file does not exist..." << endl << "...creating a new file" << endl; file.open(fileName, ios::in | ios::out | ios::binary | ios::trunc); } } int main() { char fileName[MAX]; cout << "Opening a file" << endl; fstream file; start(file, fileName); file.seekg(0, file.end); int length = file.tellg(); file.seekg(0, file.beg); bool error = false;//checks for errors if (length == 0) { cout << "The file is empty!" << endl; return 0; } bool isString; int columns = maxCol(file); file.clear(); file.seekg(0, file.beg); Grid* cells = new Grid[length + 1]; int comma = 0; //commas how many times a comma is found int column = 1, row = 1; bool isNumber; char ch; int j = 0, k = 0; char* buff = new char[length + 1]; //a temporary buffer which is used // to contain the elements which will //be extracted while (file) // a loop which goes over the file and extracts { // the symbols and puts them in differtent cells ch = file.get(); if (ch == '"' && j == 0) { isNumber = false; isString = false; ch = file.get(); } else if (j == 0) isNumber = true; if (ch == '\\') ch = file.get(); if (file.peek() == ',' && ch != '"' && isNumber==false) isNumber = true; else if (ch == '"' && isNumber == false) isString = true; if ((ch != ',' && ch != ' ' && ch != '\n' && ch != '"') || isNumber == false && (ch == ' ' || isString == false && (ch == ',' || ch == '"'))) { buff[j] = ch; j++; if (ch == ',') ch = file.get(); } if (ch == ',') { comma++; if (j != 0) { buff[j] = { '\0' }; cells[k].setContent(buff); } else { cells[k].setContent(""); } cells[k].setRow(row); cells[k].setColumn(column); if (isNumber == true) if (cells[k].checkStr(cells[k]) == false || isString==false) { cells[k].printError(); error = true; isString = true; } ++column; j = 0; k++; } if (ch == '\n' || length == file.tellg()) { if (j != 0 || (j == 0 && comma == columns)) { buff[j] = { '\0' }; cells[k].setContent(buff); cells[k].setRow(row); cells[k].setColumn(column); if (isNumber == true) if (cells[k].checkStr(cells[k]) == false || isString==false) { cells[k].printError(); error = true; isString = true; } column++; comma++; k++; j = 0; } if (j == 0) { while (comma <= columns) { cells[k].setContent(""); cells[k].setRow(row); cells[k].setColumn(column); column++; comma++; k++; } } column = 1; comma = 0; row++; } } if (error == true) { system("pause"); return 0; } delete[] buff; calculateCells(cells, k); int command, result = 0; do // loop which reads the command from the user { print_menu(); command = read_command(); if (command < 0) command = 0; result = execute_command(command, file, fileName, k, cells); } while (result == 0); system("pause"); return 0; }
// // Created by wqy on 19-12-17. // #include "SignalAction.h" using namespace esc; int SignalAction::getID() { return 2; }
#include <WiFi.h> #include <stdio.h> #include <AzureIoTHub.h> #include <apps/sntp/sntp.h> #include "blink.h" #include "logging.h" #include "device_configuration.h" #include "iot_device_core.h" #include "iot_device_connection.h" #ifndef IOTDEVICE_PROTOCOL_MQTT #define IOTDEVICE_PROTOCOL_MQTT #endif #define IOTDEVICE_DIAGNOSTIC_SAMPLING_PERCENTAGE 0 //Setting the auto URL Encoder (recommended for MQTT). Please use this option unless //you are URL Encoding inputs yourself. //ONLY valid for use with MQTT #ifndef IOTDEVICE_AUTO_URL_ENCODE_DECODE && (defined PROTOCOL_MQTT || defined PROTOCOL_MQTT_WS) #define IOTDEVICE_AUTO_URL_ENCODE_DECODE true #endif IOTHUB_CLIENT_LL_HANDLE __hub_client_handle__; #ifdef IOTDEVICE_PROTOCOL_MQTT #include <AzureIoTProtocol_MQTT.h> #include <iothubtransportmqtt.h> IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = MQTT_Protocol; #endif // IOTDEVICE_PROTOCOL_MQTT #ifdef IOTDEVICE_PROTOCOL_HTTP #include <AzureIoTProtocol_HTTP.h> #include <iothubtransporthttp.h> IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = HTTP_Protocol; #endif // IOTDEVICE_PROTOCOL_HTTP int receiveContext; bool clientConnected = false; static void IoTDevice_ConnectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void *user_context) { clientConnected = false; switch (reason) { case IOTHUB_CLIENT_CONNECTION_EXPIRED_SAS_TOKEN: if (result == IOTHUB_CLIENT_CONNECTION_UNAUTHENTICATED) { Log_Info(">>> Connection status: timeout"); } break; case IOTHUB_CLIENT_CONNECTION_DEVICE_DISABLED: break; case IOTHUB_CLIENT_CONNECTION_BAD_CREDENTIAL: break; case IOTHUB_CLIENT_CONNECTION_RETRY_EXPIRED: break; case IOTHUB_CLIENT_CONNECTION_NO_NETWORK: if (result == IOTHUB_CLIENT_CONNECTION_UNAUTHENTICATED) { Log_Info(">>> Connection status: disconnected"); } break; case IOTHUB_CLIENT_CONNECTION_COMMUNICATION_ERROR: break; case IOTHUB_CLIENT_CONNECTION_OK: if (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED) { clientConnected = true; Log_Info(">>> Connection status: connected"); } break; } } void IoTDevice_ConnectWifi(const char *ssid, const char *password) { Log_Info("Starting connecting WiFi: %s", ssid); BlinkLed_High(); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); printf("."); } printf("\n"); Log_Info("Connected on WiFi"); Log_Debug("IP address: %s", WiFi.localIP().toString().c_str()); BlinkLed_Low(); } static void IoTDevice_InitDeviceTime() { Log_Info("Initializing Device Time"); sntp_setoperatingmode(SNTP_OPMODE_POLL); const char *ntpHostName = DeviceConfiguration_Get("ntp", "hostname", 256); if (String(ntpHostName).equals("")) { ntpHostName = "pool.ntp.org"; } Log_Debug("Adding SNTP host: %s", ntpHostName); sntp_setservername(0, (char *) ntpHostName); sntp_init(); time_t ts = 0; // Before 1980 is uninitialized while (ts < 10 * 365 * 24 * 3600) { BlinkLed_Blink(); BlinkLed_Blink(); Log_Info("Waiting for SNTP initialization"); delay(1000); ts = time(NULL); } Log_Info("SNTP initialization complete."); return; } static void IoTDevice_ConfigureOption(const char *optionName, const void *value) { Log_Trace("Setting %s", optionName); Log_Debug("%s = %s", optionName, value); IOTHUB_CLIENT_RESULT result = IoTHubDeviceClient_LL_SetOption(__hub_client_handle__, optionName, value); if (result == IOTHUB_CLIENT_OK){ return; } const char * resultCode = IoTDevice_GetErrorText(result); Log_Error("Unable to set %s => %s", optionName, resultCode); free((char *)resultCode); } /* -- ConfigureOptions -- * Configures the LL Device client options. */ static void IoTDevice_ConfigureOptions() { // Set any option that are neccessary. // For available options please see the iothub_sdk_options.md documentation in the main C SDK // turn off diagnostic sampling int diag_off = 0; IoTDevice_ConfigureOption(OPTION_DIAGNOSTIC_SAMPLING_PERCENTAGE, &diag_off); #if not defined IOTDEVICE_PROTOCOL_HTTP and LOGGING_LOG_LEVEL == LOG_LEVEL_TRACE // Example sdk status tracing for troubleshooting bool traceOn = true; IoTDevice_ConfigureOption(OPTION_LOG_TRACE, &traceOn); #endif // IOTDEVICE_PROTOCOL_HTTP // Setting the Trusted Certificate. const char *certPath = DeviceConfiguration_Get("core", "caPath", 256); size_t certificatesLen; const char *content = DeviceConfiguration_GetFileContent(certPath, &certificatesLen); IoTDevice_ConfigureOption(OPTION_TRUSTED_CERT, content); #ifdef IOTDEVICE_PROTOCOL_MQTT //Setting the auto URL Encoder (recommended for MQTT). Please use this option unless //you are URL Encoding inputs yourself. //ONLY valid for use with MQTT bool urlEncodeOn = true; IoTDevice_ConfigureOption(OPTION_AUTO_URL_ENCODE_DECODE, &urlEncodeOn); #endif // IOTDEVICE_PROTOCOL_MQTT // Setting connection status callback to get indication of connection to iothub (void)IoTHubDeviceClient_LL_SetConnectionStatusCallback(__hub_client_handle__, IoTDevice_ConnectionStatusCallback, NULL); // Setting device twin callback (void)IoTHubDeviceClient_LL_SetDeviceTwinCallback(__hub_client_handle__, IoTDevice_DeviceTwinCallback, NULL); IoTDevice_RegisterDeviceMethodCallback(); } static void IoTDevice_ConnectToHub(const char *connectionString) { #ifdef IOTDEVICE_PROTOCOL_MQTT Log_Info("Loading the MQTT_Protocol Transport provider"); #endif // IOTDEVICE_PROTOCOL_MQTT #ifdef IOTDEVICE_PROTOCOL_HTTP Log_Info("Loading the HTTP_Protocol Transport provider"); #endif // IOTDEVICE_PROTOCOL_HTTP // Used to initialize IoTHub SDK subsystem (void)IoTHub_Init(); // Create the iothub handle here __hub_client_handle__ = IoTHubDeviceClient_LL_CreateFromConnectionString(connectionString, protocol); LogInfo("Creating IoTHub Device handle\r\n"); if (__hub_client_handle__ == NULL) { LogInfo("Error AZ002: Failure creating Iothub device. Hint: Check you connection string.\r\n"); return; } IoTDevice_ConfigureOptions(); IoTHubDeviceClient_LL_DoWork(__hub_client_handle__); ThreadAPI_Sleep(500); IoTHubDeviceClient_LL_GetTwinAsync(__hub_client_handle__, IoTDevice_DeviceTwinCallback, NULL); } bool IoTDevice_IsConnected(){ IoTHubDeviceClient_LL_DoWork(__hub_client_handle__); return clientConnected && __twin_received__; } void IoTDevice_ConnectFromConfiguration() { DeviceConfiguration_Init(); BlinkLed_Init(); const char *ssid = DeviceConfiguration_Get("core", "ssid", 128); const char *password = DeviceConfiguration_Get("core", "password", 128); IoTDevice_ConnectWifi(ssid, password); IoTDevice_InitDeviceTime(); const char *connectionString = DeviceConfiguration_Get("core", "connectionString", 256); IoTDevice_ConnectToHub(connectionString); }
#include "lista.h" void wczytaj_liste(string nazwa , Lista *&glowa, int & ilosc ) { ilosc=0; ifstream plik; Lista *akt, *ogon; akt=NULL; glowa=NULL; do_wczytania( nazwa.c_str() , plik ); while( !plik.eof() ) { ogon=akt; akt=new Lista; plik>>akt->dana.poziomr; plik>>akt->dana.czasr; if(ogon==NULL) glowa=akt; else ogon->next=akt; akt->next=NULL; ilosc++; } } void usun_liste(Lista *glowa) { Lista *pom; while(glowa!=NULL) { pom=glowa; glowa=glowa->next; delete pom; } } void usun( int Lp, Lista *&glowa) { Lista *akt, *poprz; if(Lp==1) { akt=glowa; glowa=glowa->next; delete akt; }else { akt=glowa; for(int i=0; i<Lp-1; i++) { poprz=akt; akt=akt->next; } poprz->next=akt->next; delete akt; } } void zapisz_liste(string nazwa, Lista *adres ) { ofstream plik(nazwa.c_str()); plik.clear(); while(adres!=NULL) { plik << adres->dana.poziomr<<endl; plik << adres->dana.czasr<<endl; adres = adres->next; } plik.close(); }
#ifndef APPLIANCE_H #define APPLIANCE_H #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <ctime> #include <vector> using namespace std; //========================================= //== Global Variables (settings) // string DELIM = "------------------------------------------"; // string DELIM; extern string DELIM; enum a_state { ON, OFF, STANDBY, OVERRIDE }; // ON - appliance has consumed power in the past minute // OFF - appliance has NOT consumed power in the past minute // STANDBY - device has shut off appliance, aka "shed" // OVERRIDE - manual override; customer has forced "on" //========================================= //== Appliance class Appliance{ public: //-constructors Appliance(string type); ~Appliance(){ if(infile.is_open()){ infile.close(); } } //-input files int open_file(string filename); int open_file(int f_index); int random_file(); //-read files int next_line(); int read_all(); //-was used for testing //-operation/communication bool is_override(){ //-check for override if(current_state == OVERRIDE){ return(true); } else{ return(false); } } bool enter_standby(); //-attempt to enter standby state; reterns true on success bool exit_standby(); //-lifts "standby" mode, re-enters "on" state void update_state(); //-updates current_state based on Balance and current_state //-check state and determine if the appliance wants to spend energy double spent(); //-determine how much energy WAS spent in the last minute void to_spend(); //-determine how much energy WILL BE spent double spend_energy();//-modify Balance to reflect upcoming energy consumption //-dump information (for testing) void dump_data(){ /* print energy of each time_entry in history */ int i; for (i=0;i<history.size();i++){ cout << history[i].energy << endl; } } void dump_nonempty(){ /* print all lines with a non-zero load --also calculates LOAD based on average of these values ---currently using hard-coded (assigned) values for LOAD */ int i; for (i=0;i<history.size();i++){ if (history[i].energy > 0){ cout << history[i].energy << endl; avg_L += history[i].energy; avg_N++; } } // LOAD = avg_L/avg_N; } // protected: ifstream infile; double LOAD; //-power consumption of the appliance double Balance; //-running total of energy that needs to be spent double spend; //-amount of energy to be consumed in the upcoming minute bool needs_to_run; //-used to check if appliance needs to run double avg_L; int avg_N; string ID; int minutes_standby; int prev_time; a_state current_state; string current_fname; vector <string> datafiles; vector <time_entry> history; //--input files vector <string> CC_filelist; vector <string> HV_filelist; vector <string> PP_filelist; vector <string> WH_filelist; int num_CC_files; int num_HV_files; int num_PP_files; int num_WH_files; }; #endif
#include "Edge.h" Edge::Edge() { src=dst=0; cost = 0.0f; } Edge::Edge( GraphNode *sourceNode, GraphNode *destinationNode, float theCost ) { src = sourceNode ; dst = destinationNode ; cost = theCost ; }
// counting sort // _ ____ __ _ _ __ // (_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_ // /( .-/ .-/ // (_) (_/ (_/ #include "../_library_sort_.h" // Độ phức tạp: // Best: O(n + k) | Avarage: O(n + k) | Worst: O(n + k) | Memory: O(n + k) | Stable // Ưu điểm: // - Nhanh // - Tối ưu khi sort mảng số nguyên dương // Nhược điểm: // - Không dùng được với chuỗi // - Cần tốn thêm bộ nhớ // - Hạn chế với dữ liệu lớn template<class T> void CountingSort(T *&arr, lli n) { // Check mảng dương for (lli i = 0; i < n; i++) { if (arr[i] < 0) { // Có phần tử âm return; } } T *output = new T[n]; T max = arr[0]; T min = arr[0]; lli i; // Tìm max, min for (i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } else if (arr[i] < min) { min = arr[i]; } } // Mảng đếm lli numElements = max - min + 1; T *count = new T[numElements]{0}; // Đếm các phần tử for (i = 0; i < n; i++) { count[arr[i] - min]++; } // count[i] += count[i - 1] for (i = 1; i < numElements; i++) { count[i] += count[i - 1]; } // Đổ lại mảng output for (i = 0; i < n; i++) { lli index = count[(arr[i] - min)]; output[index - 1] = arr[i]; count[arr[i] - min]--; } // Trả lại mảng gốc delete arr; arr = output; output = nullptr; delete output; } int main() { lli *arr; lli n{}; Input(arr, n); CountingSort(arr, n); Output(arr, n); return 0; }
#include "ExitGame.h" ExitGame::ExitGame() : std::exception("Thank you for playing the game. Goodbye!\n") { }
#include <evdsptc.h> #include "evdtest.h" #include <stdio.h> #include <assert.h> #include <fcntl.h> #include <sys/stat.h> #include <CppUTest/CommandLineTestRunner.h> #include <CppUTest/TestHarness.h> #include <CppUTestExt/MockSupport.h> #define USLEEP_PERIOD (10000) #define NUM_OF_USLEEP (10) extern "C" { extern evdtest_context_t* evdtest_getcontext(void); } static volatile int count = 0; static volatile int relay_count = 0; static bool countup(evdsptc_event_t* event){ (void)event; count++; EVDTEST_POSTEVENT("count=%d", count); return true; } static bool relay(evdsptc_event_t* event){ evdsptc_context_t* ctx; evdsptc_event_t* ev; relay_count++; ctx = (evdsptc_context_t*)evdsptc_event_getparam(event); ev = (evdsptc_event_t*)malloc(sizeof(evdsptc_event_t)); evdsptc_event_init(ev, countup, NULL, true, evdsptc_event_free); evdsptc_post(ctx, ev); EVDTEST_POSTEVENT("relay-%d", relay_count); return true; } static bool check_test_done(bool expect){ int fd; struct stat st; bool is_done; fd = open(EVDTEST_DONE_FILE, O_RDONLY); assert(fstat(fd, &st) == 0); is_done = (st.st_size > 0); CHECK_EQUAL(expect, is_done); return expect == is_done; } TEST_GROUP(evdtest_test_group){ void setup(){ count = 0; relay_count = 0; } void teardown(){ mock().checkExpectations(); mock().clear(); setenv(EVDTEST_ENV_TEST_CASE, "", 1); } }; TEST(evdtest_test_group, start_error_envarg_empty_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; ret_start = evdtest_start(NULL, NULL); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NOT_FOUND, ret_start); CHECK_EQUAL(EVDTEST_ERROR_NOT_FOUND, ret_stop); check_test_done(false); } TEST(evdtest_test_group, start_error_bad_lua_script_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_error.lua", 1); ret_start = evdtest_start(NULL, NULL); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_BAD_LUA_SCRIPT, ret_start); CHECK_EQUAL(EVDTEST_ERROR_BAD_LUA_SCRIPT, ret_stop); check_test_done(false); } TEST(evdtest_test_group, start_error_runtime_lua_script_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_runtime_error.lua", 1); ret_start = evdtest_start(NULL, NULL); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_ANY_LUA_EXCEPTIONS, ret_stop); check_test_done(false); } static volatile bool done = false; static bool handle_timer(evdsptc_event_t* event){ (void) event; EVDTEST_POSTEVENT("hello world"); return done; } TEST(evdtest_test_group, start_and_join_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_normal.lua", 1); evdsptc_context_t ctx; evdsptc_event_t ev; struct timespec interval = { interval.tv_sec = 0, interval.tv_nsec = 1 * 1000 * 1000}; evdsptc_create_periodic(&ctx, NULL, NULL, NULL, &interval); evdsptc_event_init(&ev, handle_timer, NULL, false, NULL); ret_start = evdtest_start(NULL, NULL); evdsptc_post(&ctx, &ev); ret_stop = evdtest_join(); done = true; evdsptc_event_waitdone(&ev); evdsptc_destroy(&ctx, true); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_stop); check_test_done(true); } TEST(evdtest_test_group, lua_postevent_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_postevent.lua", 1); ret_start = evdtest_start(NULL, NULL); CHECK_EQUAL(EVDTEST_ERROR_NONE, EVDTEST_POSTEVENT("hello world")); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_stop); check_test_done(true); } TEST(evdtest_test_group, abort_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_postevent.lua", 1); ret_start = evdtest_start(NULL, NULL); evdtest_abort(); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_ANY_LUA_EXCEPTIONS, ret_stop); check_test_done(false); } TEST(evdtest_test_group, timeout_main_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_timeout_main.lua", 1); ret_start = evdtest_start(NULL, NULL); CHECK_EQUAL(EVDTEST_ERROR_NONE, EVDTEST_POSTEVENT("hello world")); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_ANY_LUA_EXCEPTIONS, ret_stop); check_test_done(false); } TEST(evdtest_test_group, timeout_coroutine_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_timeout_coroutine.lua", 1); ret_start = evdtest_start(NULL, NULL); CHECK_EQUAL(EVDTEST_ERROR_NONE, EVDTEST_POSTEVENT("hello world")); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_ANY_LUA_EXCEPTIONS, ret_stop); check_test_done(false); } TEST(evdtest_test_group, ignore_cancel_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_ignore_cancel.lua", 1); ret_start = evdtest_start(NULL, NULL); CHECK_EQUAL(EVDTEST_ERROR_NONE, EVDTEST_POSTEVENT("hello world")); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_stop); check_test_done(true); } TEST(evdtest_test_group, residue_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; setenv(EVDTEST_ENV_TEST_CASE, "lua/test_residue.lua", 1); ret_start = evdtest_start(NULL, NULL); CHECK_EQUAL(EVDTEST_ERROR_NONE, EVDTEST_POSTEVENT("hello world")); ret_stop = evdtest_join(); evdtest_destroy(); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_ANY_LUA_EXCEPTIONS, ret_stop); check_test_done(false); } TEST(evdtest_test_group, capture_test){ evdtest_error_t ret_start = EVDTEST_ERROR_NONE; evdtest_error_t ret_stop = EVDTEST_ERROR_NONE; evdsptc_context_t ctx_relay; evdsptc_context_t ctx_countup; evdsptc_event_t* ev; int i = 0; evdsptc_create(&ctx_relay, NULL, NULL, NULL); evdsptc_create(&ctx_countup, NULL, NULL, NULL); setenv(EVDTEST_ENV_TEST_CASE, "lua/test_capture.lua", 1); ret_start = evdtest_start(NULL, NULL); EVDTEST_POSTEVENT("hello world"); for(i = 0; i <= 9; i++){ ev = (evdsptc_event_t*)malloc(sizeof(evdsptc_event_t)); evdsptc_event_init(ev, relay, (void*)&ctx_countup, true, evdsptc_event_free); evdsptc_post(&ctx_relay, ev); } CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_start); CHECK_EQUAL(EVDTEST_ERROR_NONE, ret_stop); ret_stop = evdtest_join(); evdsptc_destroy(&ctx_relay, true); evdsptc_destroy(&ctx_countup, true); evdtest_destroy(); check_test_done(true); } int main(int ac, char** av){ return CommandLineTestRunner::RunAllTests(ac, av); }
#ifndef RODINBTNODEACTIONDECORATOR_H #define RODINBTNODEACTIONDECORATOR_H #include "rodinbtnodedecorator.h" #include "array.h" class WBAction; class RodinBTNodeActionDecorator : public RodinBTNodeDecorator { public: RodinBTNodeActionDecorator(); virtual ~RodinBTNodeActionDecorator(); DEFINE_RODINBTNODE_FACTORY( ActionDecorator ); virtual void InitializeFromDefinition( const SimpleString& DefinitionName ); virtual void OnStart(); virtual void OnFinish(); private: Array<WBAction*> m_StartActions; Array<WBAction*> m_FinishActions; }; #endif // RODINBTNODEACTIONDECORATOR_H
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; int a[n], dp[n][2]; for(int i=0; i<n; i++) cin>>a[i]; dp[0][0] = 0; dp[0][1] = 0; for(int i=1; i<n; i++) { dp[i][0] = dp[i-1][1]+a[i-1]-1; dp[i][1] = max(a[i]-1+dp[i-1][0], abs(a[i]-a[i-1])+dp[i-1][1]); } cout<<max(dp[n-1][0], dp[n-1][1])<<endl; } }
// // Created by matan on 1/14/20. // #ifndef SOLID_SERVER_REDO_ISEARCHABLE_H #define SOLID_SERVER_REDO_ISEARCHABLE_H #include "../State.h" #include "../Position.h" #include <vector> using namespace std; template<class Position> class ISearchable { public: virtual State<Position> *getInitialState() = 0; virtual State<Position> *getGoalState() = 0; virtual double calcHeuristic(State<Position> *current) = 0; virtual bool isGoalState(State<Position> *state) = 0; virtual string toString() = 0; virtual vector<State<Position> *> getAllPossibleStates(State<Position> *state) = 0; }; #endif //SOLID_SERVER_REDO_ISEARCHABLE_H
#include "../include/puzzle.h" enum puzzle::zero_movement puzzle::oppositeMovement(enum puzzle::zero_movement dir) { switch(dir) { case puzzle::ZERO_UP: return puzzle::ZERO_DOWN; case puzzle::ZERO_DOWN: return puzzle::ZERO_UP; case puzzle::ZERO_LEFT: return puzzle::ZERO_RIGHT; case puzzle::ZERO_RIGHT: return puzzle::ZERO_LEFT; default: break; } return puzzle::ZERO_NONE; } puzzle::puzzle(const initializer_list<initializer_list<puzzle::element_type>>& elementList) : tam(elementList.size()) , table(new puzzle::element_type*[tam]) , storage(new puzzle::element_type[tam * tam]) , distances(new puzzle::element_type*[tam]) { int j, i = 0; for(auto& it: elementList) { if (it.size() != static_cast<unsigned int>(tam)) throw -1; table[i] = &storage[i * tam]; distances[i] = new puzzle::element_type[tam]; j = 0; for(auto piece: it) { if (piece == 0) { line0 = i; column0 = j; } table[i][j] = piece; ++j; } ++i; } compute_manhattan_dist(); } puzzle::puzzle(puzzle::element_type *puzz, int tam) { this->tam = tam; this->table = new puzzle::element_type*[tam]; this->storage = new puzzle::element_type[tam * tam]; this->distances = new puzzle::element_type*[tam]; for(int i=0; i<tam; i++) { table[i] = &storage[i * tam]; distances[i] = new puzzle::element_type[tam]; for(int j=0; j<tam; j++) { int piece = puzz[i*tam+j]; if(piece == 0) { line0 = i; column0 = j; } table[i][j] = piece; } } compute_manhattan_dist(); } puzzle::puzzle(const vector<vector<puzzle::element_type>>& elements) : tam(elements.size()) , table(new puzzle::element_type*[tam]) , storage(new puzzle::element_type[tam * tam]) , distances(new puzzle::element_type*[tam]) { for(unsigned int i = 0; i < elements.size(); ++i) { table[i] = &storage[i * tam]; distances[i] = new puzzle::element_type[tam]; for(unsigned int j = 0; j < elements.size(); ++j) { if (elements[i][j] == 0) { line0 = i; column0 = j; } table[i][j] = elements[i][j]; } } compute_manhattan_dist(); } puzzle::puzzle(int tam) : table(new puzzle::element_type*[tam]) , storage(new puzzle::element_type[tam * tam]) , distances(new puzzle::element_type*[tam]) { int i, j; puzzle::element_type aux; vector<puzzle::element_type> random_pieces(tam * tam); this->tam = tam; // Aleatorizar peças. for (i = tam * tam - 1; i > -1; --i) random_pieces[i] = i; shuffle(random_pieces.begin() , random_pieces.end() , default_random_engine(chrono::system_clock::now().time_since_epoch().count()) ); // Aloca espaço no vetor (opcional, mas é mais rápido). for (i = 0; i < tam; ++i) { table[i] = &storage[i * tam]; distances[i] = new puzzle::element_type[tam]; } // Inicializa o quebra-cabeça com valores aleatórios. for (i = 0; i < tam; ++i) { for (j = 0; j < tam; ++j) { aux = random_pieces[i * tam + j]; table[i][j] = aux; if (aux == 0) { line0 = i; column0 = j; } } } compute_manhattan_dist(); } puzzle::puzzle(const puzzle &original) : tam(original.tam) , line0(original.line0) , column0(original.column0) , totalDistance(0) , table(new puzzle::element_type*[tam]) , storage(new puzzle::element_type[tam * tam]) , distances(new puzzle::element_type*[tam]) { int i,j; for (i = 0; i < tam; ++i) { table[i] = &storage[i * tam]; distances[i] = new puzzle::element_type[tam]; for (j = 0; j < tam; ++j) { table[i][j] = original.table[i][j]; distances[i][j] = original.distances[i][j]; } } compute_manhattan_dist(); } puzzle::~puzzle() { int i; for(i = 0; i < tam; i++) { delete [] distances[i]; } delete [] table; delete [] storage; delete [] distances; } int puzzle::properLine(int pieceNum){ return (pieceNum - 1) / tam; } int puzzle::properColumn(int pieceNum){ return (pieceNum - 1) % tam ; } int puzzle::pieceNum(int column, int line){ return tam * line + column + 1; } bool puzzle::check_solve() { return ( ((tam % 2 == 1) && (inversion() % 2 == 0)) || ((tam % 2 == 0) && (((tam - line0) % 2 == 1) == (inversion() % 2 == 0))) ); // FORMULA DE SOLUCIONABILIDADE } void puzzle::compute_manhattan_dist() { int i, j; totalDistance = 0; for(i = 0; i < tam; i++){ for(j = 0;j < tam; j++){ manhattan_update(i, j); totalDistance += distances[i][j]; } } } int puzzle::manhattan_dist() const { return totalDistance; } bool puzzle::isMoveValid(enum zero_movement move) { switch(move) { case ZERO_UP: return line0 != 0; case ZERO_DOWN: return line0 != tam - 1; case ZERO_LEFT: return column0 != 0; case ZERO_RIGHT: return column0 != tam - 1; default: break; } return false; } int puzzle::move_zero(enum zero_movement dir) { int num; switch(dir) { case ZERO_UP: if(line0 == 0) return -1; num = table[line0-1][column0]; table[line0][column0] = num; line0--; table[line0][column0] = 0; manhattan_update(line0+1, column0); break; case ZERO_DOWN: if(line0 == tam - 1) return -1; num = table[line0+1][column0]; table[line0][column0] = num; line0++; table[line0][column0] = 0; manhattan_update(line0-1, column0); break; case ZERO_LEFT: if(column0 == 0) return -1; num = table[line0][column0-1]; table[line0][column0] = num; column0--; table[line0][column0] = 0; manhattan_update(line0, column0+1); break; case ZERO_RIGHT: if(column0 == tam - 1) return -1; num = table[line0][column0+1]; table[line0][column0] = num; column0++; table[line0][column0] = 0; manhattan_update(line0, column0-1); break; default: return -1; } manhattan_update(line0, column0); return 0; } int puzzle::inversion(){ int i, j, preceding, successor; int inv = 0; for(i = 1; i < tam * tam; i++) { preceding = table[properLine(i)][properColumn(i)]; for(j = i + 1; j <= tam * tam; j++) { successor = table[properLine(j)][properColumn(j)]; if (successor != 0 && preceding > successor) inv++; } } return inv; } string puzzle::toString(){ stringstream stream; int i, j; for(i = 0; i < tam; ++i) { stream << (int)table[i][0]; for(j = 1; j < tam; ++j) stream << ",\t" << (int)table[i][j]; stream << "\n"; } return stream.str(); } void puzzle::manhattan_update(int line, int column) { puzzle::element_type value = table[line][column]; puzzle::element_type formerDistance = distances[line][column]; if (value == 0) distances[line][column] = 0; else distances[line][column] = abs(line-properLine(value)) + abs(column-properColumn(value)); totalDistance += distances[line][column] - formerDistance; } int puzzle::getTam() { return tam; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTCONTINUUMMECHANICSNEUMANNBCSASSEMBLER_HPP_ #define TESTCONTINUUMMECHANICSNEUMANNBCSASSEMBLER_HPP_ #include <cxxtest/TestSuite.h> #include "ContinuumMechanicsNeumannBcsAssembler.hpp" #include "PetscSetupAndFinalize.hpp" class TestContinuumMechanicsNeumannBcsAssembler : public CxxTest::TestSuite { public: void TestAssembler2d() { QuadraticMesh<2> mesh; TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/canonical_triangle_quadratic", 2, 2, false); mesh.ConstructFromMeshReader(mesh_reader); ContinuumMechanicsProblemDefinition<2> problem_defn(mesh); double t1 = 2.6854233; double t2 = 3.2574578; // for the boundary element on the y=0 surface, create a traction std::vector<BoundaryElement<1,2>*> boundary_elems; std::vector<c_vector<double,2> > tractions; c_vector<double,2> traction; traction(0) = t1; traction(1) = t2; for (TetrahedralMesh<2,2>::BoundaryElementIterator iter = mesh.GetBoundaryElementIteratorBegin(); iter != mesh.GetBoundaryElementIteratorEnd(); ++iter) { if (fabs((*iter)->CalculateCentroid()[1])<1e-4) { BoundaryElement<1,2>* p_element = *iter; boundary_elems.push_back(p_element); tractions.push_back(traction); } } assert(boundary_elems.size()==1); problem_defn.SetTractionBoundaryConditions(boundary_elems, tractions); ContinuumMechanicsNeumannBcsAssembler<2> assembler(&mesh, &problem_defn); TS_ASSERT_THROWS_THIS(assembler.AssembleVector(), "Vector to be assembled has not been set"); Vec bad_sized_vec = PetscTools::CreateVec(2); assembler.SetVectorToAssemble(bad_sized_vec, true); TS_ASSERT_THROWS_THIS(assembler.AssembleVector(), "Vector provided to be assembled has size 2, not expected size of 18 ((dim+1)*num_nodes)"); Vec vec = PetscTools::CreateVec(3*mesh.GetNumNodes()); assembler.SetVectorToAssemble(vec, true); assembler.AssembleVector(); ReplicatableVector vec_repl(vec); // Note: on a 1d boundary element, intgl phi_i dx = 1/6 for the bases on the vertices // and intgl phi_i dx = 4/6 for the basis at the interior node. (Here the integrals // are over the canonical 1d element, [0,1], which is also the physical element for this // mesh. // node 0 is on the surface, and is a vertex TS_ASSERT_DELTA(vec_repl[0], t1/6.0, 1e-8); TS_ASSERT_DELTA(vec_repl[1], t2/6.0, 1e-8); // node 1 is on the surface, and is a vertex TS_ASSERT_DELTA(vec_repl[3], t1/6.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4], t2/6.0, 1e-8); // nodes 2, 3, 4 are not on the surface for (unsigned i=2; i<5; i++) { TS_ASSERT_DELTA(vec_repl[3*i], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[3*i], 0.0, 1e-8); } // node 5 is on the surface, and is an interior node TS_ASSERT_DELTA(vec_repl[15], 4*t1/6.0, 1e-8); TS_ASSERT_DELTA(vec_repl[16], 4*t2/6.0, 1e-8); // the rest of the vector is the pressure block and should be zero. TS_ASSERT_DELTA(vec_repl[2], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[5], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[8], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[11], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[14], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[17], 0.0, 1e-8); PetscTools::Destroy(vec); PetscTools::Destroy(bad_sized_vec); } void TestAssembler3d() { QuadraticMesh<3> mesh(1.0, 1.0, 1.0, 1.0); ContinuumMechanicsProblemDefinition<3> problem_defn(mesh); double t1 = 2.6854233; double t2 = 3.2574578; double t3 = 4.5342308; // for the boundary element on the z=0 surface, create a traction std::vector<BoundaryElement<2,3>*> boundary_elems; std::vector<c_vector<double,3> > tractions; c_vector<double,3> traction; traction(0) = t1; traction(1) = t2; traction(2) = t3; for (TetrahedralMesh<3,3>::BoundaryElementIterator iter = mesh.GetBoundaryElementIteratorBegin(); iter != mesh.GetBoundaryElementIteratorEnd(); ++iter) { if (fabs((*iter)->CalculateCentroid()[2])<1e-4) { BoundaryElement<2,3>* p_element = *iter; boundary_elems.push_back(p_element); tractions.push_back(traction); } } assert(boundary_elems.size()==2); problem_defn.SetTractionBoundaryConditions(boundary_elems, tractions); Vec vec = PetscTools::CreateVec(4*mesh.GetNumNodes()); ContinuumMechanicsNeumannBcsAssembler<3> assembler(&mesh, &problem_defn); assembler.SetVectorToAssemble(vec, true); assembler.AssembleVector(); ReplicatableVector vec_repl(vec); // For boundary elements in 3d - ie for 2d elements - and with QUADRATIC basis functions, we have // \intgl_{canonical element} \phi_i dV = 0.0 for i=0,1,2 (ie bases on vertices) // and // \intgl_{canonical element} \phi_i dV = 1/6 for i=3,4,5 (ie bases on mid-nodes) for (unsigned i=0; i<mesh.GetNumNodes(); i++) { double x = mesh.GetNode(i)->rGetLocation()[0]; double y = mesh.GetNode(i)->rGetLocation()[1]; double z = mesh.GetNode(i)->rGetLocation()[2]; if (fabs(z) < 1e-8) // ie if z=0 { if (fabs(x-0.5)<1e-8 || fabs(y-0.5)<1e-8) // if x=0.5 or y=0.5 { unsigned num_surf_elems_contained_in = 1; if (fabs(x+y-1.0) < 1e-8) // if x=0.5 AND y=0.5 { num_surf_elems_contained_in = 2; } // interior node on traction surface TS_ASSERT_DELTA(vec_repl[4*i], num_surf_elems_contained_in * t1/6.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+1], num_surf_elems_contained_in * t2/6.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+2], num_surf_elems_contained_in * t3/6.0, 1e-8); } else { TS_ASSERT_DELTA(vec_repl[4*i], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+1], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+2], 0.0, 1e-8); } } else { TS_ASSERT_DELTA(vec_repl[4*i], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+1], 0.0, 1e-8); TS_ASSERT_DELTA(vec_repl[4*i+2], 0.0, 1e-8); } } for (unsigned i=0; i<mesh.GetNumNodes(); i++) { TS_ASSERT_DELTA(vec_repl[4*i+3], 0.0, 1e-8); } PetscTools::Destroy(vec); } void TestAssemblerMeshType() { TetrahedralMesh<2,2> mesh; ContinuumMechanicsProblemDefinition<2> problem_defn(mesh); TS_ASSERT_THROWS_CONTAINS(ContinuumMechanicsNeumannBcsAssembler<2>(&mesh, &problem_defn), "Continuum mechanics solvers require a quadratic mesh"); TetrahedralMesh<3,3> mesh3d; ContinuumMechanicsProblemDefinition<3> problem_defn3d(mesh3d); TS_ASSERT_THROWS_CONTAINS(ContinuumMechanicsNeumannBcsAssembler<3>(&mesh3d, &problem_defn3d), "Continuum mechanics solvers require a quadratic mesh"); } }; #endif // TESTCONTINUUMMECHANICSNEUMANNBCSASSEMBLER_HPP_
#include "Compiler.h" void Compiler::GenerateTokens(const char* input_file, const char* output_file, const char* id_table, const char* label_table) { Compiler::LexicalUnit::CLexicalUnit clu; clu.GenerateTokens(input_file, output_file, id_table, label_table); }
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { string str1 = "3333311111111111"; string str2 = "44422222221111"; reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); cout<<str1<<endl<<str2; strigstream ss1(str1); strigstream ss2(str2); string temp,temp2; string sum; while(!ss1.eof() && !ss2.eof()) { ss1>>temp1; ss2>>temp2; } }
#include "searcha.h" /* A collection of graph search algorithms. The graph is unweighted and directed and represented as an adjacency list, al. The variable al is a vector of vetors */ #include <iostream> #include <stack> #include <queue> using namespace std; /* Perform breadth-first-search. */ void bfs ( const vector < vector<int> > &al , int x0) { /* INPUT: al is an adjacency list representation of the graph x0 is the initial vertex to begin search */ /* Arrays for status of processed, discovered, and the parent IDs */ int n = al.size(); // number of nodes vector<bool> processed(n, false); vector<bool> discovered(n, false); vector<int> parent(n, -1); /* Initialize */ int s = x0; queue<int> q; q.push(s); discovered[s] = true; /*** SEARCH ***/ while ( !q.empty() ) { s = q.front(); q.pop(); // current vertex /* process vertex early */ cout << "Processing vertex " << s << endl; /* process neighbors to queue */ for (int t : al[s]) { if (!processed[t]) { cout << "Processing edge " << s << " -> " << t << endl; } if (!discovered[t]) { parent[t] = s; q.push(t); discovered[t] = true; } } processed[s] = true; } // end of while } /* Perform depth-first-search. */ void dfs ( const vector < vector<int> > &al , int x0) { /* INPUT: al is an adjacency list representation of the graph x0 is the initial vertex to begin search */ /* Arrays for status of processed, discovered, and the parent IDs */ int n = al.size(); // number of nodes vector<bool> processed(n, false); vector<bool> discovered(n, false); vector<int> parent(n, -1); /* Initialize */ int s = x0; stack<int> q; q.push(s); discovered[s] = true; /*** SEARCH ***/ while ( !q.empty() ) { s = q.top(); q.pop(); // current vertex /* process vertex early */ cout << "Processing vertex " << s << endl; /* process neighbors to queue */ for (int t : al[s]) { if (!processed[t]) { cout << "Processing edge " << s << " -> " << t << endl; } if (!discovered[t]) { parent[t] = s; q.push(t); discovered[t] = true; } } processed[s] = true; } // end of while }
/* * WordGenerator.h * * Created on: Nov 11, 2013 * Author: vbonnici */ /* * the same of DNA4WordGenerator but can input/output words in std::string type */ #ifndef WORDGENERATOR_H_ #define WORDGENERATOR_H_ namespace dolierlib{ class WordGenerator{ int k; int m; dna5_t *dkmer; dna5_t *ckmer; int *mi; int si; std::string s; public: WordGenerator(std::string base, int m){ this->m = m; k = base.length(); dkmer = to_dna5(base); ckmer = new dna5_t[k]; mi = new int[k]; si = 0; mi[0] = 0; ckmer[0] = DNA5Alphabet::A; s = ""; } WordGenerator(dna5_t *base, int k, int m){ this->m = m; this-> k = k; dkmer = new dna5_t[k]; for(int i=0; i<k; i++) dkmer[i] = base[i]; ckmer = new dna5_t[k]; mi = new int[k]; si = 0; mi[0] = 0; ckmer[0] = DNA5Alphabet::A; s = ""; } ~WordGenerator(){ delete [] dkmer; delete [] ckmer; delete [] mi; } std::string word(){ return s; } bool next(){ if(si>=0){ int miss = 0; while(si >= 0){ // std::cout<<si<<"\t"<<((int)(ckmer[si] + 1))<<"\n"; ckmer[si] = (ckmer[si] + 1); if(ckmer[si]>4){ si--; } else{ miss = (ckmer[si]-1 != dkmer[si]) ? 1 : 0; if(mi[si] + miss <= m){ if(si == k-1){ s = ""; for(int i=0; i<k; i++){ s = s + DNA5Alphabet::symbolFor(ckmer[i] - 1); } return true; } else{ ckmer[si+1] = DNA5Alphabet::A; mi[si+1] = mi[si] + miss; si++; } } } } return false; } else return false; } }; } #endif /* WORDGENERATOR_H_ */
/* * SPDX-FileCopyrightText: 2019 Rolf Eike Beer <eike@sf-mail.de> * * SPDX-License-Identifier: GPL-3.0-or-later */ #pragma once #include "cache_set.h" struct relation_object_replacer { osm_t * const osm; const object_t &old; const object_t &replace; relation_object_replacer(osm_t *o, const object_t &t, const object_t &n) : osm(o), old(t), replace(n) {} inline void operator()(std::pair<item_id_t, relation_t *> pair) { operator()(pair.second); } void operator()(relation_t *r); }; struct find_member_object_functor { const object_t &object; explicit inline find_member_object_functor(const object_t &o) : object(o) {} inline bool operator()(const member_t &member) { return member.object == object; } }; extern cache_set value_cache; ///< the cache for key, value, and role strings
#include "player.h" #include <string> #include <iostream> player::player(){ name="Reimu Harukei"; hpstat=750; atkstat=65; spatkstat=80; defstat=50; spdefstat=55; hp=hpstat; atk=atkstat; spatk=spatkstat; def=defstat; spdef=spdefstat; } player::player(std::string initialname, int initialhp, int initialatk, int initialspatk, int initialspdef, int initialdef){ name=initialname; hpstat=initialhp; atkstat=initialatk; spatkstat=initialspatk; defstat=initialdef; spdefstat=initialspdef; hp=hpstat; atk=atkstat; spatk=spatkstat; def=defstat; spdef=spdefstat; } void player::basicattack(){ ismagic=false; dmgout=5; std::cout<<name<<" Attacks with a basic attack!"<<std::endl<<std::endl; } void player::attack1(){ ismagic=false; dmgout=15; std::cout<<name<<" Used Supersonic Elemental Drill!"<<std::endl<<std::endl; } void player::attack2(){ ismagic=true; dmgout=15; hp=hp+100+rand()%150; checkhpover(); std::cout<<name<<" Used Demon Sealing Prayer: Holy Life Steal!"<<std::endl<<std::endl; } void player::attack3(){ ismagic=true; dmgout=35; std::cout<<name<<" Used Max Power Bullet Barrage!"<<std::endl<<std::endl; atk=atk+5; } void player::attack4(){ ismagic=true; dmgout=100+rand()%76; std::cout<<name<<" Used Eastern Spell of the Gensokyo Magical Girls: Bullet Hell!"<<std::endl<<std::endl; } void player::levelup(){ spatk=spatk+10; atk=atk+10; def=def+15; spdef=spdef+15; spatkstat=spatkstat+10; atkstat=atkstat+10; defstat=defstat+15; spdefstat=spdefstat+15; hpstat=hpstat+130; hp=hpstat; std::cout<<" "<<std::endl; std::cout<<"The vanquished enemy soul strengthens your magic." <<std::endl; std::cout<<"Your HP has been replenished"<<std::endl<<std::endl; } player::~player(){ }
/* * ball.cpp * * Created on: 11. dec. 2016 * Author: dusted */ #include "ball.hpp" Ball::Ball(SDL_Texture *tex, SDL_Rect rect, float x, float y, float velx, float vely) { this->rect = rect; this->posx = x; this->posy = y; this->velx = velx; this->vely = vely; this->texture = tex; } void Ball::move(float time) { this->posx += this->velx*time; this->posy += this->vely*time; if( this->vely < 50) this->vely += 1; } void Ball::draw(SDL_Renderer* ren) { this->rect.x = int(this->posx); this->rect.y = int(this->posy); SDL_RenderCopy(ren, this->texture, NULL, &this->rect); } void Ball::reactInsideBox( int fx, int fy, int tx, int ty) { if(this->posx < fx ) { this->velx *= -0.9; this->posx = fx; } else if( this->posx+this->rect.w > tx) { this->velx *= -0.9; this->posx = tx - this->rect.w; } if(this->rect.y < fy ) { this->vely = 0; this->posy = fy; } else if((this->rect.y+this->rect.h) > ty) { this->vely *= -0.7; this->velx /=1.8; this->posy = ty - this->rect.h; if( fabs(this->vely) < 10 ) { this->vely *=5; } } if( fabs(this->velx) < 6 ) { this->velx *=5; } }
//--------------------------------------------------------------------------- #ifndef Unit2H #define Unit2H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include "WebModuleUnit1.h" //--------------------------------------------------------------------------- class TWebModule2 : public TWebModule1 { __published: // Composants gérés par l'EDI private: // Déclarations utilisateur public: // Déclarations utilisateur __fastcall TWebModule2(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TWebModule2 *WebModule2; //--------------------------------------------------------------------------- #endif
#include<bits/stdc++.h> #define maxn 200005 #define maxm 25 #define mod 1000000007 #define int long long using namespace std; int f[maxm+2][maxn]; int cur[maxn]; int a[maxn], b[maxn], len[maxn]; signed main() { int n, m, k; cin >> n >> m >> k; for(int i=0; i<n; i++) scanf("%lld",&a[i]); b[0] = a[0]%k; f[0][0]++; for(int i=1; i<n; i++) { b[i] = (b[i-1]+a[i])%k; f[0][b[i-1]%k]++; f[0][b[i-1]%k] %= mod; } int tmp = b[n-1]; for(int i=0; i<maxm; i++) { len[i] = tmp; tmp *= 2; tmp %= k; } for(int i=1; i<maxm; i++) { for(int j=0; j<k; j++) { f[i][j] = (f[i-1][j]+f[i-1][(j-len[i-1]+k)%k])%mod; } } tmp = 0; for(int i=maxm-1; i>=0; i--) { if(!(m&(1ll<<i))) continue; for(int j=0; j<k; j++) { cur[j] += f[i][(j-tmp+k)%k]; cur[j] %= mod; } tmp += len[i]; tmp %= k; } int ans = 0; if(tmp == 0) { cur[0]--; cur[0] += mod; cur[0] %= mod; ans += cur[0]; ans %= mod; cur[tmp]++; cur[tmp] %= mod; for (int i=0; i<n-1; i++) { cur[b[i]]--; cur[b[i]] += mod; cur[b[i]] %= mod; ans += cur[b[i]]; ans %= mod; cur[(tmp+b[i])%k]++; cur[(tmp+b[i])%k] %= mod; } ans=ans*m%mod; ans++; } else { cur[0]--; cur[0] += mod; cur[0] %= mod; ans += cur[0]; ans %= mod; cur[tmp]++; cur[tmp] %= mod; for (int i=0; i<n-1; i++) { cur[b[i]]--; cur[b[i]] += mod; cur[b[i]] %= mod; ans += cur[b[i]]; ans %= mod; cur[(tmp+b[i])%k]++; cur[(tmp+b[i])%k] %= mod; } ans=ans*m%mod; } cout << ans <<endl; }
#include "String.hpp" #include "StringUtility.hpp" #include "Exception.hpp" #include <cstring> #include <cstdio> namespace engine { StringImpl::StringImpl() : m_size(0) , m_buffer(0) , m_capacity(0) {} StringImpl::StringImpl(const char* cstr) { m_size = StringLen(cstr); if (m_size == 0) { return; } Alloc(m_size + 1); // copy string and null termination std::memcpy(m_buffer, cstr, m_capacity); } StringImpl::StringImpl(const char* cstr, Uint32 size) { #if DEBUG_BUILD Uint32 len = StringLen(cstr); ASSERT(len > size); #endif m_size = size; Alloc(m_size + 1); std::memcpy(m_buffer, cstr, m_size); m_buffer[m_size] = '\0'; } StringImpl::StringImpl(const StringImpl& str) { Alloc(str.m_capacity); m_size = str.m_size; std::memcpy(m_buffer, str.m_buffer, m_capacity); } StringImpl::StringImpl(StringImpl&& str) { m_buffer = str.m_buffer; str.m_buffer = nullptr; m_size = str.m_size; str.m_size = 0; m_capacity = str.m_capacity; str.m_capacity = 0; } Int64 StringImpl::ToInt64(Uint32 startPos, Uint32& endPos) { return StringToInt64(m_buffer, nullptr); } StringImpl StringImpl::Strip() const { if (m_buffer == nullptr) { return StringImpl(); } const char* startPtr = m_buffer; while(*startPtr != '\0' && (*startPtr < 33 || *startPtr > 126)) { startPtr++; } const char* endPtr = m_buffer + m_size; while(endPtr != startPtr && (*endPtr < 33 || *endPtr > 126)) { endPtr--; } return StringImpl(startPtr, endPtr - startPtr); } String StringImpl::operator+(const String& other) const { StringImpl str; str.m_capacity = str.m_size = m_size + other.m_size; str.m_buffer = new char[str.m_size]; std::memcpy(str.m_buffer, m_buffer, m_size); std::memcpy(str.m_buffer + m_size, other.m_buffer, other.m_size); return str; } StringImpl& StringImpl::operator=(const char* str) { // maybe new object???? Uint32 strLen = StringLen(str); Clear(); Alloc(strLen + 1); std::memcpy(m_buffer, str, m_capacity); return *this; } StringImpl& StringImpl::operator=(const StringImpl& str) { Clear(); Alloc(str.m_size + 1); std::memcpy(m_buffer, str.m_buffer, m_capacity); return *this; } StringImpl& StringImpl::operator=(StringImpl&& str) { Clear(); std::swap(m_size, str.m_size); std::swap(m_capacity, str.m_capacity); std::swap(m_buffer, str.m_buffer); return *this; } void StringImpl::Alloc(Uint32 size) { m_buffer = new char[size]; m_capacity = size; } bool StringImpl::Realloc(Uint32 size) { char* new_buffer = reinterpret_cast<char*>(realloc(m_buffer, size)); if (new_buffer != nullptr) { m_buffer = new_buffer; return true; } else { return false; } } void StringImpl::Clear() { if (m_buffer != nullptr) { delete[] m_buffer; m_size = 0; m_capacity = 0; } } namespace impl { #include <stdarg.h> StringImpl FormatImpl(const char* format, ...) { constexpr Uint32 bufferSize = 256; char buffer[256]; va_list args; va_start(args, format); int ret = vsnprintf(buffer,256,format, args); va_end(args); if (ret < bufferSize && ret >= 0) { StringImpl str(buffer); return str; } else if (ret < 0) { throw InvalidArgument("Invalid format", 0); return StringImpl(); } else { throw InvalidArgument("Buffer to small", 1); return StringImpl(); } } } //namespace impl } // namespace engine
#include <iostream> using namespace std; int main() { double a, b; cin >> a >> b; cout << fixed; //cout.setf(ios::fixed); 같은기능 cout.precision(6); cout << "첫 번째 수 : " << a << '\n'; cout << "두 번째 수 : " << b << '\n'; cout << "합 : " << a + b; //a,b의 자료형이 float이면 2.999999로 출력됨 }
// // 17837_RE.cpp // Algorithm // // Created by 박세은 on 2020/06/03. // Copyright © 2020 박세은. All rights reserved. // /* 17837. 새로운 게임 다시풀기2 */ #include <iostream> #include <vector> using namespace std; struct horseInfo { int r, c, dir; horseInfo(){} horseInfo(int rr, int cc, int dd) { r = rr; c = cc; dir = dd; } }; int N, K, rr, cc, dd, turn = 0; int board[13][13]; vector<int> chess[13][13]; vector<horseInfo> horse; int dr[5] = {0,0,0,-1,1}; int dc[5] = {0,1,-1,0,0}; int reverseDir(int d) { if(d == 1) return 2; if(d == 2) return 1; if(d == 3) return 4; else return 3; } bool moveHorse(int idx, int r, int c, int nr, int nc, int type) { if(type == 1) { while (!chess[r][c].empty()) { int h = chess[r][c].back(); chess[nr][nc].push_back(h); chess[r][c].pop_back(); horse[h].r = nr; horse[h].c = nc; if(h == idx) break; } } else if(type == 0) { vector<int> v; while (!chess[r][c].empty()) { int h = chess[r][c].back(); v.push_back(h); chess[r][c].pop_back(); horse[h].r = nr; horse[h].c = nc; if(h == idx) break; } for(int j = v.size()-1; j >= 0 ; j--) { chess[nr][nc].push_back(v[j]); } } if(chess[nr][nc].size() >= 4) return true; else return false; } bool game_start() { while (turn <= 1000) { turn++; for(int i = 0; i < K; i++) { int d = horse[i].dir; int nr = horse[i].r + dr[d]; int nc = horse[i].c + dc[d]; if(nr < 1 || nr > N || nc < 1 || nc > N || board[nr][nc] == 2) { // 방향 바꾸고 d = reverseDir(d); horse[i].dir = d; nr += dr[d]*2; nc += dc[d]*2; } if(nr < 1 || nr > N || nc < 1 || nc > N || board[nr][nc] == 2) continue; if(moveHorse(i, horse[i].r, horse[i].c, nr, nc, board[nr][nc])) return true; } } return false; } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N >> K; for(int i = 1; i <= N; i++) for(int j = 1; j <= N; j++) cin >> board[i][j]; for(int i = 0; i < K; i++) { cin >> rr >> cc >> dd; horse.push_back(horseInfo(rr, cc, dd)); chess[rr][cc].push_back(i); } if(game_start()) cout << turn; else cout << -1; return 0; }
#include <cstdio> using namespace std; // A binary heap is a binary tree that is completely filled and satisfy heap order property. // In a Min(Max) heap, for every node X, the key in the parent of X is smaller(larger) or equal to the key in X, with the exception of root (which has no parent). // For element at index i, its left child has index 2i+1, its right child has index 2i+2, its parent has index (i-1)/2 class BinHeap { int capacity; // maximum heap size int size; // current number of element in the heap int *harr; // pointer to array of elements in the heap public: BinHeap(int capacity); // constructor 1 ~BinHeap(); // deconstructor void buildHeap(int n, int* arr); // build the heap from an input N keys void makeEmpty(); // remove all keys from the min heap void insert(int x); // insert new key to the min heap void deleteMin(); // remove the minimun key from the min heap int findMin(); // return the minimun key from the min heap bool isEmpty(); // return if the heap is empty bool isFull(); // return if the heap is full void decreaseKey(int p, int delta); // decrease the value of the key at position p void increaseKey(int p, int delta); // increase the value of the keay at postion p }; BinHeap::BinHeap(int cap) { capacity = cap; size = 0; harr = new int[cap]; } BinHeap::~BinHeap() { delete [] harr; } void BinHeap::buildHeap(int n, int* arr) { if (n > capacity) { printf("Heap is full\n"); return; } size = n; for (int i = 0; i < n; i++) { harr[i] = arr[i]; } // interate to percolate down the non-leaf node for (int i = (size-2)/2; i >=0; i--) { int j, child; int ele = harr[i]; for (j = i; 2*j+1 < size; j = child) { child = 2*j + 1; if (child + 1 < size; harr[child+1] < harr[child]) { child ++; } if (ele > harr[child]) { harr[j] = harr[child]; } else { break; } } harr[j] = ele; } } void BinHeap::makeEmpty() { size = 0; } void BinHeap::insert(int x) { // To insert an element X into the heap, we create a hole in the next available location since other wise the tree will not be complete. If X can be placed in the hole without violating heap order, then we do so and are done. Otherwise we slide the element that is in the hole's parent node into the hoe, thus bubbling the hole up towards the root. We continue this process until X can be placed in the hole. // This general strategy is known as a 'percolate up'. if (this->isFull()) { printf("BinHeap is full\n"); return; } size += 1; int i = size - 1; while (i != 0 && x < harr[(i-1)/2]) { harr[i] = harr[(i-1)/2]; i = (i-1) / 2; } harr[i] = x; } void BinHeap::deleteMin() { // When the minimun is removed, a hole is created at the root. Since the heap now becomes one smaller, it follows that the last element X in the heap must move somewhere in the heap. If X can be placed in the hole, the we are done. Otherwise we slide the smaller o the hole's children into the hole, thus pushing the hole down one level. We repeat this step until X can be placed in the hole. // This general strategy is known as a 'percolate down'. if (this->isEmpty()) { printf("BinHeap is empty\n"); return; } int lastEle = harr[--size]; int i, child; for (i = 0; 2*i+1 < size; i = child) { child = 2 * i + 1; if (child < size-1 && harr[child+1] < harr[child]) { child ++; } if (lastEle > harr[child]) { harr[i] = harr[child]; } else { break; } } harr[i] = lastEle; } int BinHeap::findMin() { if (this->isEmpty()) { printf("Heap is empty\n"); return -1; } return harr[0]; } bool BinHeap::isEmpty() { return size == 0; } bool BinHeap::isFull() { return size == capacity; } void BinHeap::decreaseKey(int p, int delta) { // Since lowering the value of the key at position p by a positive amount delta might violate the heap order, it must be fixed by a percolate up. int x = harr[p] - delta; int i = p; while (i != 0 && x < harr[(i-1)/2]) { harr[i] = harr[(i-1)/2]; i = (i-1) / 2; } harr[i] = x; } void BinHeap::increaseKey(int p, int delta) { // Since increasing the value of the key at positoin p by a positive amount delta might violate the heap order, it must be fixed by a percolate down. int x = harr[p] + delta; int i, child; for (i = p; 2*i+1 < size; i = child) { child = 2*i + 1; if (child+1 < size && harr[child+1] < harr[child]) { child ++; } if (x > harr[child]) { harr[i] = harr[child]; } else { break; } } harr[i] = x; } int main() { BinHeap* bh = new BinHeap(20); int a[15] = {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130}; bh->buildHeap(15, a); bh->insert(160); bh->insert(0); while (!bh->isEmpty()) { int d = bh->findMin(); bh->deleteMin(); printf("%d\n", d); } return 0; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef media_attr_str_h #define media_attr_str_h #include <multimedia/codec.h> namespace YUNOS_MM { #define DEFINE_MEDIA_MIMETYPE(TYPE) extern const char* MEDIA_MIMETYPE_##TYPE; #define DEFINE_MEDIA_ATTR(TYPE) extern const char* MEDIA_ATTR_##TYPE; #define DEFINE_MEDIA_META(TYPE) extern const char* MEDIA_META_##TYPE; // mimetype DEFINE_MEDIA_MIMETYPE(IMAGE_JPEG) DEFINE_MEDIA_MIMETYPE(IMAGE_PNG) DEFINE_MEDIA_MIMETYPE(IMAGE_BMP) DEFINE_MEDIA_MIMETYPE(IMAGE_GIF) DEFINE_MEDIA_MIMETYPE(IMAGE_WEBP) DEFINE_MEDIA_MIMETYPE(IMAGE_WBMP) DEFINE_MEDIA_MIMETYPE(VIDEO_VP3) DEFINE_MEDIA_MIMETYPE(VIDEO_VP5) DEFINE_MEDIA_MIMETYPE(VIDEO_VP6) DEFINE_MEDIA_MIMETYPE(VIDEO_VP6A) DEFINE_MEDIA_MIMETYPE(VIDEO_VP6F) DEFINE_MEDIA_MIMETYPE(VIDEO_VP7) DEFINE_MEDIA_MIMETYPE(VIDEO_VP8) DEFINE_MEDIA_MIMETYPE(VIDEO_VP9) DEFINE_MEDIA_MIMETYPE(VIDEO_AVC) DEFINE_MEDIA_MIMETYPE(VIDEO_HEVC) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG4) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG4V1) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG4V2) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG4V3) DEFINE_MEDIA_MIMETYPE(VIDEO_H263) DEFINE_MEDIA_MIMETYPE(VIDEO_H263_P) DEFINE_MEDIA_MIMETYPE(VIDEO_H263_I) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG2) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG2_XVMC) DEFINE_MEDIA_MIMETYPE(VIDEO_MPEG1) DEFINE_MEDIA_MIMETYPE(VIDEO_H261) DEFINE_MEDIA_MIMETYPE(VIDEO_RV10) DEFINE_MEDIA_MIMETYPE(VIDEO_RV20) DEFINE_MEDIA_MIMETYPE(VIDEO_RV30) DEFINE_MEDIA_MIMETYPE(VIDEO_RV40) DEFINE_MEDIA_MIMETYPE(VIDEO_MJPEG) DEFINE_MEDIA_MIMETYPE(VIDEO_MJPEGB) DEFINE_MEDIA_MIMETYPE(VIDEO_LJPEG) DEFINE_MEDIA_MIMETYPE(VIDEO_JPEGGLS) DEFINE_MEDIA_MIMETYPE(VIDEO_SP5X) DEFINE_MEDIA_MIMETYPE(VIDEO_WMV) DEFINE_MEDIA_MIMETYPE(VIDEO_WMV1) DEFINE_MEDIA_MIMETYPE(VIDEO_WMV2) DEFINE_MEDIA_MIMETYPE(VIDEO_WMV3) DEFINE_MEDIA_MIMETYPE(VIDEO_WMV3IMAGE) DEFINE_MEDIA_MIMETYPE(VIDEO_VC1) DEFINE_MEDIA_MIMETYPE(VIDEO_FLV) DEFINE_MEDIA_MIMETYPE(VIDEO_DV) DEFINE_MEDIA_MIMETYPE(VIDEO_HUFFYUV) DEFINE_MEDIA_MIMETYPE(VIDEO_CYUV) DEFINE_MEDIA_MIMETYPE(VIDEO_INDEOX) DEFINE_MEDIA_MIMETYPE(VIDEO_THEORA) DEFINE_MEDIA_MIMETYPE(VIDEO_TIFF) DEFINE_MEDIA_MIMETYPE(VIDEO_GIF) DEFINE_MEDIA_MIMETYPE(VIDEO_DVB) DEFINE_MEDIA_MIMETYPE(VIDEO_FLASH) DEFINE_MEDIA_MIMETYPE(VIDEO_RAW) DEFINE_MEDIA_MIMETYPE(CONTAINER_WVM) DEFINE_MEDIA_MIMETYPE(CONTAINER_WAV) DEFINE_MEDIA_MIMETYPE(CONTAINER_MPEG2PS) DEFINE_MEDIA_MIMETYPE(CONTAINER_OGG) DEFINE_MEDIA_MIMETYPE(CONTAINER_AVI) DEFINE_MEDIA_MIMETYPE(CONTAINER_MATROSKA) DEFINE_MEDIA_MIMETYPE(CONTAINER_MPEG4) DEFINE_MEDIA_MIMETYPE(CONTAINER_MPEG2TS) DEFINE_MEDIA_MIMETYPE(AUDIO_AAC_ADTS) DEFINE_MEDIA_MIMETYPE(AUDIO_AAC_LATM) DEFINE_MEDIA_MIMETYPE(AUDIO_AMR_NB) DEFINE_MEDIA_MIMETYPE(AUDIO_3GPP) DEFINE_MEDIA_MIMETYPE(AUDIO_WMALOSSLESS) DEFINE_MEDIA_MIMETYPE(AUDIO_AMR_WB) DEFINE_MEDIA_MIMETYPE(AUDIO_WMAPRO) DEFINE_MEDIA_MIMETYPE(AUDIO_MPEG) // layer III DEFINE_MEDIA_MIMETYPE(AUDIO_MPEG_ADU) // layer III DEFINE_MEDIA_MIMETYPE(AUDIO_MPEG_ON4) // layer III DEFINE_MEDIA_MIMETYPE(AUDIO_WMA) DEFINE_MEDIA_MIMETYPE(AUDIO_MPEG_LAYER_I) DEFINE_MEDIA_MIMETYPE(AUDIO_WAV) DEFINE_MEDIA_MIMETYPE(AUDIO_MPEG_LAYER_II) DEFINE_MEDIA_MIMETYPE(AUDIO_WMV) DEFINE_MEDIA_MIMETYPE(AUDIO_AAC) DEFINE_MEDIA_MIMETYPE(AUDIO_MP3) DEFINE_MEDIA_MIMETYPE(AUDIO_ADTS_PROFILE) DEFINE_MEDIA_MIMETYPE(AUDIO_MP2) DEFINE_MEDIA_MIMETYPE(AUDIO_QCELP) DEFINE_MEDIA_MIMETYPE(AUDIO_DRA288) DEFINE_MEDIA_MIMETYPE(AUDIO_VORBIS) DEFINE_MEDIA_MIMETYPE(AUDIO_DRA144) DEFINE_MEDIA_MIMETYPE(AUDIO_OPUS) DEFINE_MEDIA_MIMETYPE(AUDIO_DTSHD) DEFINE_MEDIA_MIMETYPE(AUDIO_G711_ALAW) DEFINE_MEDIA_MIMETYPE(AUDIO_EC3) DEFINE_MEDIA_MIMETYPE(AUDIO_G711_MLAW) DEFINE_MEDIA_MIMETYPE(AUDIO_AC3) DEFINE_MEDIA_MIMETYPE(AUDIO_RAW) DEFINE_MEDIA_MIMETYPE(AUDIO_MSGSM) DEFINE_MEDIA_MIMETYPE(AUDIO_FLAC) DEFINE_MEDIA_MIMETYPE(AUDIO_DTS) DEFINE_MEDIA_MIMETYPE(TEXT_3GPP) DEFINE_MEDIA_MIMETYPE(TEXT_SUBRIP) DEFINE_MEDIA_MIMETYPE(TEXT_VTT) DEFINE_MEDIA_MIMETYPE(TEXT_CEA_608) DEFINE_MEDIA_ATTR(FILE_MAJOR_BAND) DEFINE_MEDIA_ATTR(FILE_MINOR_VERSION) DEFINE_MEDIA_ATTR(FILE_COMPATIBLE_BRANDS) DEFINE_MEDIA_ATTR(FILE_CREATION_TIME) DEFINE_MEDIA_ATTR(MIME) DEFINE_MEDIA_ATTR(CONTAINER) DEFINE_MEDIA_ATTR(CODECID) DEFINE_MEDIA_ATTR(CODECTAG) DEFINE_MEDIA_ATTR(STREAMCODECTAG) DEFINE_MEDIA_ATTR(CODECPROFILE) DEFINE_MEDIA_ATTR(CODEC_CONTEXT) DEFINE_MEDIA_ATTR(CODEC_CONTEXT_MUTEX) DEFINE_MEDIA_ATTR(TARGET_TIME) //component mimeType DEFINE_MEDIA_MIMETYPE(AUDIO_RENDER) DEFINE_MEDIA_MIMETYPE(VIDEO_RENDER) DEFINE_MEDIA_MIMETYPE(MEDIA_DEMUXER) DEFINE_MEDIA_MIMETYPE(MEDIA_APP_SOURCE) DEFINE_MEDIA_MIMETYPE(MEDIA_RTP_DEMUXER) DEFINE_MEDIA_MIMETYPE(MEDIA_DASH_DEMUXER) DEFINE_MEDIA_MIMETYPE(MEDIA_MUXER) DEFINE_MEDIA_MIMETYPE(MEDIA_RTP_MUXER) DEFINE_MEDIA_MIMETYPE(VIDEO_SOURCE) DEFINE_MEDIA_MIMETYPE(AUDIO_SOURCE) DEFINE_MEDIA_MIMETYPE(AUDIO_SOURCE_FILE) DEFINE_MEDIA_MIMETYPE(VIDEO_TEST_SOURCE) DEFINE_MEDIA_MIMETYPE(VIDEO_UVC_SOURCE) DEFINE_MEDIA_MIMETYPE(VIDEO_FILE_SOURCE) DEFINE_MEDIA_MIMETYPE(VIDEO_WFD_SOURCE) DEFINE_MEDIA_MIMETYPE(VIDEO_SCREEN_SOURCE) DEFINE_MEDIA_MIMETYPE(VIDEO_SURFACE_SOURCE) DEFINE_MEDIA_MIMETYPE(MEDIA_FILE_SINK) DEFINE_MEDIA_MIMETYPE(IMAGE_CAMERA_SOURCE) DEFINE_MEDIA_MIMETYPE(MEDIA_CAMERA_SOURCE) DEFINE_MEDIA_MIMETYPE(SUBTITLE_SOURCE) DEFINE_MEDIA_MIMETYPE(SUBTITLE_SINK) DEFINE_MEDIA_MIMETYPE(MEDIA_EXTERNAL_SOURCE) // media attributes DEFINE_MEDIA_ATTR(AAC_PROFILE) DEFINE_MEDIA_ATTR(BIT_RATE) DEFINE_MEDIA_ATTR(BIT_RATE_AUDIO) DEFINE_MEDIA_ATTR(BIT_RATE_VIDEO) DEFINE_MEDIA_ATTR(CHANNEL_COUNT) DEFINE_MEDIA_ATTR(CHANNEL_MASK) DEFINE_MEDIA_ATTR(SAMPLE_FORMAT) DEFINE_MEDIA_ATTR(COLOR_FORMAT) DEFINE_MEDIA_ATTR(COLOR_FOURCC) DEFINE_MEDIA_ATTR(DURATION) DEFINE_MEDIA_ATTR(FLAC_COMPRESSION_LEVEL) DEFINE_MEDIA_ATTR(FRAME_RATE) DEFINE_MEDIA_ATTR(HEIGHT) DEFINE_MEDIA_ATTR(IS_ADTS) DEFINE_MEDIA_ATTR(IS_AUTOSELECT) DEFINE_MEDIA_ATTR(IS_DEFAULT) DEFINE_MEDIA_ATTR(IS_FORCED_SUBTITLE) DEFINE_MEDIA_ATTR(I_FRAME_INTERVAL) DEFINE_MEDIA_ATTR(LANGUAGE) DEFINE_MEDIA_ATTR(MAX_HEIGHT) DEFINE_MEDIA_ATTR(SLICE_HEIGHT) DEFINE_MEDIA_ATTR(MAX_INPUT_SIZE) DEFINE_MEDIA_ATTR(MAX_WIDTH) DEFINE_MEDIA_ATTR(MAX_FILE_SIZE) DEFINE_MEDIA_ATTR(MAX_DURATION) DEFINE_MEDIA_ATTR(PUSH_BLANK_BUFFERS_ON_STOP) DEFINE_MEDIA_ATTR(REPEAT_PREVIOUS_FRAME_AFTER) DEFINE_MEDIA_ATTR(SAMPLE_RATE) DEFINE_MEDIA_ATTR(WIDTH) DEFINE_MEDIA_ATTR(PREVIEW_WIDTH) DEFINE_MEDIA_ATTR(PREVIEW_HEIGHT) DEFINE_MEDIA_ATTR(IMAGE_WIDTH) DEFINE_MEDIA_ATTR(IMAGE_HEIGHT) DEFINE_MEDIA_ATTR(STRIDE) DEFINE_MEDIA_ATTR(STRIDE_X) DEFINE_MEDIA_ATTR(STRIDE_Y) DEFINE_MEDIA_ATTR(CROP_RECT) DEFINE_MEDIA_ATTR(VOLUME) DEFINE_MEDIA_ATTR(MUTE) DEFINE_MEDIA_ATTR(AVG_FRAMERATE) DEFINE_MEDIA_ATTR(AVC_PROFILE) DEFINE_MEDIA_ATTR(AVC_LEVEL) DEFINE_MEDIA_ATTR(HEVC_PROFILE) DEFINE_MEDIA_ATTR(HEVC_LEVEL) DEFINE_MEDIA_ATTR(IDR_FRAME) DEFINE_MEDIA_ATTR(AUDIO_SOURCE) DEFINE_MEDIA_ATTR(STREAM_INDEX) DEFINE_MEDIA_ATTR(AUDIO_SAMPLES) DEFINE_MEDIA_ATTR(SAMPLE_ASPECT_RATION) DEFINE_MEDIA_ATTR(CHANNEL_LAYOUT) DEFINE_MEDIA_ATTR(DECODE_MODE) DEFINE_MEDIA_ATTR(DECODE_THUMBNAIL) DEFINE_MEDIA_ATTR(THUMB_PATH) DEFINE_MEDIA_ATTR(THUMB_WIDTH) DEFINE_MEDIA_ATTR(THUMB_HEIGHT) DEFINE_MEDIA_ATTR(MICROTHUMB_PATH) DEFINE_MEDIA_ATTR(MICROTHUMB_WIDTH) DEFINE_MEDIA_ATTR(MICROTHUMB_HEIGHT) DEFINE_MEDIA_ATTR(COVER_PATH) DEFINE_MEDIA_ATTR(MIME_AUDIO_3GPP) DEFINE_MEDIA_ATTR(MIME_AUDIO_QUICKTIME) DEFINE_MEDIA_ATTR(MIME_AUDIO_MP4) DEFINE_MEDIA_ATTR(MIME_VIDEO_3GPP) DEFINE_MEDIA_ATTR(MIME_VIDEO_QUICKTIME) DEFINE_MEDIA_ATTR(MIME_VIDEO_MP4) DEFINE_MEDIA_ATTR(ALBUM) DEFINE_MEDIA_ATTR(HAS_AUDIO) DEFINE_MEDIA_ATTR(HAS_VIDEO) DEFINE_MEDIA_ATTR(HAS_COVER) DEFINE_MEDIA_ATTR(ATTACHEDPIC) DEFINE_MEDIA_ATTR(ATTACHEDPIC_SIZE) DEFINE_MEDIA_ATTR(ATTACHEDPIC_CODECID) DEFINE_MEDIA_ATTR(ATTACHEDPIC_MIME) DEFINE_MEDIA_ATTR(YES) DEFINE_MEDIA_ATTR(NO) DEFINE_MEDIA_ATTR(TITLE) DEFINE_MEDIA_ATTR(SUBTITLE) DEFINE_MEDIA_ATTR(AUTHOR) DEFINE_MEDIA_ATTR(COMMENT) DEFINE_MEDIA_ATTR(DESCRIPTION) DEFINE_MEDIA_ATTR(CATEGORY) DEFINE_MEDIA_ATTR(GENRE) DEFINE_MEDIA_ATTR(YEAR) DEFINE_MEDIA_ATTR(DATE) DEFINE_MEDIA_ATTR(USER_RATING) DEFINE_MEDIA_ATTR(KEYWORDS) DEFINE_MEDIA_ATTR(PUBLISHER) DEFINE_MEDIA_ATTR(COPYRIGHT) DEFINE_MEDIA_ATTR(PARENTAL_RATING) DEFINE_MEDIA_ATTR(RATING_ORGANIZATION) DEFINE_MEDIA_ATTR(SIZE) DEFINE_MEDIA_ATTR(BUFFER_INDEX) DEFINE_MEDIA_ATTR(IS_VIDEO_RENDER) DEFINE_MEDIA_ATTR(VIDEO_FORCE_RENDER) DEFINE_MEDIA_ATTR(MEDIA_TYPE) DEFINE_MEDIA_ATTR(AUDIO_CODEC) DEFINE_MEDIA_ATTR(AVERAGE_LEVEL) DEFINE_MEDIA_ATTR(BLOCK_ALIGN) DEFINE_MEDIA_ATTR(PEAK_VALUE) DEFINE_MEDIA_ATTR(ALBUM_TITLE) DEFINE_MEDIA_ATTR(ALBUM_ARTIST) DEFINE_MEDIA_ATTR(CONTRIBUTING_ARTIST) DEFINE_MEDIA_ATTR(COMPOSER) DEFINE_MEDIA_ATTR(CONDUCTOR) DEFINE_MEDIA_ATTR(LYRICS) DEFINE_MEDIA_ATTR(MOOD) DEFINE_MEDIA_ATTR(TRACK_NUMBER) DEFINE_MEDIA_ATTR(TRACK_COUNT) DEFINE_MEDIA_ATTR(COVER_ART_URL_SMALL) DEFINE_MEDIA_ATTR(COVER_ART_URL_LARGE) DEFINE_MEDIA_ATTR(RESOLUTION) DEFINE_MEDIA_ATTR(VIDEO_CODEC) DEFINE_MEDIA_ATTR(POSTER_URL) DEFINE_MEDIA_ATTR(CHAPTER_NUMBER) DEFINE_MEDIA_ATTR(DIRECTOR) DEFINE_MEDIA_ATTR(LEAD_PERFORMER) DEFINE_MEDIA_ATTR(WRITER) DEFINE_MEDIA_ATTR(FILE_PATH) DEFINE_MEDIA_ATTR(FILE_HANDLE) DEFINE_MEDIA_ATTR(OUTPUT_FORMAT) DEFINE_MEDIA_ATTR(JPEG_QUALITY) DEFINE_MEDIA_ATTR(EXTRADATA0) DEFINE_MEDIA_ATTR(EXTRADATA1) DEFINE_MEDIA_ATTR(ROTATION) // in degree DEFINE_MEDIA_ATTR(CODEC_DATA) DEFINE_MEDIA_ATTR(LOCATION) DEFINE_MEDIA_ATTR(LOCATION_LATITUDE) DEFINE_MEDIA_ATTR(LOCATION_LONGITUDE) DEFINE_MEDIA_ATTR(DATETAKEN) DEFINE_MEDIA_ATTR(ORIENTATION) // Time Base // type: Fraction DEFINE_MEDIA_ATTR(TIMEBASE) DEFINE_MEDIA_ATTR(TIMEBASE2) // seek offset // type: int64 DEFINE_MEDIA_ATTR(SEEK_OFFSET) // seek whence // type: int32, it is one of the following: SEEK_SET, SEEK_CUR, SEEK_END DEFINE_MEDIA_ATTR(SEEK_WHENCE) DEFINE_MEDIA_ATTR(PALY_RATE) DEFINE_MEDIA_ATTR(VARIABLE_RATE_SUPPORT) DEFINE_MEDIA_ATTR(STREAM_IS_SEEKABLE) DEFINE_MEDIA_ATTR(START_TIME) DEFINE_MEDIA_ATTR(START_DELAY_TIME) DEFINE_MEDIA_ATTR(AVC_PROFILE_BASELINE) DEFINE_MEDIA_ATTR(AVC_PROFILE_MAIN) DEFINE_MEDIA_ATTR(AVC_PROFILE_HIGH) DEFINE_MEDIA_ATTR(AVC_PROFILE_CONSTRAINEDBASELINE) DEFINE_MEDIA_ATTR(AVC_LEVEL1) DEFINE_MEDIA_ATTR(AVC_LEVEL1b) DEFINE_MEDIA_ATTR(AVC_LEVEL11) DEFINE_MEDIA_ATTR(AVC_LEVEL12) DEFINE_MEDIA_ATTR(AVC_LEVEL13) DEFINE_MEDIA_ATTR(AVC_LEVEL2) DEFINE_MEDIA_ATTR(AVC_LEVEL21) DEFINE_MEDIA_ATTR(AVC_LEVEL22) DEFINE_MEDIA_ATTR(AVC_LEVEL3) DEFINE_MEDIA_ATTR(AVC_LEVEL31) DEFINE_MEDIA_ATTR(AVC_LEVEL32) DEFINE_MEDIA_ATTR(AVC_LEVEL4) DEFINE_MEDIA_ATTR(AVC_LEVEL41) DEFINE_MEDIA_ATTR(AVC_LEVEL42) DEFINE_MEDIA_ATTR(AVC_LEVEL5) DEFINE_MEDIA_ATTR(GOP_SIZE) DEFINE_MEDIA_META(BUFFER_TYPE) // specify MediaBuffer::MediaBufferType in MediaMeta //for camera DEFINE_MEDIA_ATTR(PHOTO_COUNT) DEFINE_MEDIA_ATTR(CAMERA_OBJECT) DEFINE_MEDIA_ATTR(RECORDING_PROXY_OBJECT) DEFINE_MEDIA_ATTR(TIME_LAPSE_ENABLE) DEFINE_MEDIA_ATTR(TIME_LAPSE_FPS) //audio device DEFINE_MEDIA_ATTR(AUDIO_SOURCE_MIC) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_VOICE_UPLINK) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_VOICE_DOWNLINK) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_VOICE_CALL) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_CAMCORDER) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_VOICE_RECOGNITION) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_VOICE_COMMUNICATION) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_REMOTE_SUBMIX) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_FM_TUNER) DEFINE_MEDIA_ATTR(AUDIO_SOURCE_CNT) DEFINE_MEDIA_ATTR(VIDEO_RAW_DATA) DEFINE_MEDIA_ATTR(VIDEO_SURFACE) DEFINE_MEDIA_ATTR(VIDEO_SURFACE_TEXTURE) DEFINE_MEDIA_ATTR(VIDEO_BQ_PRODUCER) DEFINE_MEDIA_ATTR(NATIVE_WINDOW_BUFFER) DEFINE_MEDIA_ATTR(NATIVE_DISPLAY) DEFINE_MEDIA_ATTR(INPUT_BUFFER_NUM) DEFINE_MEDIA_ATTR(INPUT_BUFFER_SIZE) DEFINE_MEDIA_ATTR(STORE_META_INPUT) DEFINE_MEDIA_ATTR(PREPEND_SPS_PPS) DEFINE_MEDIA_ATTR(STORE_META_OUTPUT) DEFINE_MEDIA_ATTR(REPEAT_FRAME_DELAY_US) DEFINE_MEDIA_ATTR(BITRATE_MODE) DEFINE_MEDIA_ATTR(MUSIC_SPECTRUM) DEFINE_MEDIA_ATTR(BUFFER_LIST) DEFINE_MEDIA_ATTR(CODEC_MEDIA_DECRYPT) DEFINE_MEDIA_ATTR(CODEC_RESOURCE_ID) DEFINE_MEDIA_ATTR(CODEC_LOW_DELAY) DEFINE_MEDIA_ATTR(CODEC_DISABLE_HW_RENDER) DEFINE_MEDIA_ATTR(CODEC_DROP_ERROR_FRAME) // when one buffer is ahead of other stream than this threshold, muxer will reject it (MM_ERROR_AGAIN). unit is ms DEFINE_MEDIA_ATTR(MUXER_STREAM_DRIFT_MAX) DEFINE_MEDIA_ATTR(FILE_DOWNLOAD_PATH) /////////////////////////////////////////////////////////////////// //codecId2Mime const char * codecId2Mime(CowCodecID id); CowCodecID mime2CodecId(const char *mime); }// namespace YUNOS_MM #endif // media_attr_str_h
// // Created by zlc on 2021/5/25. // #include "../include/part_slam/sensor_range/rangereading.h" namespace GMapping { using namespace std; // 构造函数 // n_beams 指定了激光束的数量 // d 表示各个激光的距离 // angle 每束激光的角度 // 均匀角度的激光雷达数据 // RangeReading::RangeReading(unsigned int n_beams, const double *d) // { // m_beams = n_beams; // m_dists.resize(n_beams); // for (unsigned int i=0; i<n_beams; i ++) // m_dists[i] = d[i]; // } // 不均匀角度的激光雷达数据 RangeReading::RangeReading(unsigned int n_beams, const double* d, const double* angle) { m_beams = n_beams; m_dists.resize(n_beams); m_angles.resize(n_beams); for (unsigned int i=0; i<n_beams; i ++) { m_dists[i] = d[i]; m_angles[i] = angle[i]; } } RangeReading::~RangeReading() {} };
//============================================================================ // Name : main.cpp // Author : Lei // Version : // Copyright : Your copyright notice // Description : Hello World in C++ //============================================================================ #include <iostream> #include <memory> #include <string> using namespace std; class SharedThing : public std::enable_shared_from_this<SharedThing> { public: std::string name(void) { return name_; }; #if 0 //Do not do this! creates multiple control blocks std::shared_ptr<SharedThing> getSharedThing() { return this; } #endif // Lets us vend shared pointers to *this // Requires a shared_ptr to be created before use std::shared_ptr<SharedThing> getSharedThing() { return shared_from_this(); } // factory function that perfect-forwards args // to a private ctor - we use this to create objects template <typename... Arg> static auto create(Arg&&... arg) -> std::shared_ptr<SharedThing> { struct EnableMakeShared : public SharedThing { EnableMakeShared(Arg&&... arg) : SharedThing(std::forward<Arg>(arg)...) {} }; return std::make_shared<EnableMakeShared>(std::forward<Arg>(arg)...); } private: std::string name_; // We make constructor private - shared_from_this() breaks if a shared // ptr has never been created before. (It looks for the control block) SharedThing() : name_("Nameless Thing") {} SharedThing(std::string name) : name_(name) {} }; int cppmain(void) { // Creating a shared ptr. std::shared_ptr<uint32_t> x(new uint32_t(0x1234abcd)); // Note how much cleaner the make_shared alternative is. auto y(std::make_shared<uint32_t>(0xdeadbeef)); auto z(x); // z is now a shared ptr to x via copy // Dereference ops work as expected std::cout << "x: " << std::hex << *x << std::endl; std::cout << "y: " << std::hex << *y << std::endl; std::cout << "z: " << std::hex << *z << std::endl; std::weak_ptr<uint32_t> wptr(y); // wptr is a weak pointer to y // We're going to use wptr to get to our shared_ptr, and prove it std::shared_ptr<uint32_t> sptr(wptr); // Get also works for shared_ptrs - same rules apply, you don't own it! std::cout << "y@" << std::hex << y.get() << std::endl; std::cout << "sptr@" << std::hex << sptr.get() << std::endl; sptr.reset(); // refcnt now 1 sptr = wptr.lock(); // another way to convert weak->shared - refcnt now 2 sptr = nullptr; // refcnt now 1 if (!wptr.expired()) { std::cout << "wptr is still valid" << std::endl; } else { std::cout << "wptr is expired" << std::endl; } y = nullptr; // refcnt is 0, delete y if (!wptr.expired()) { std::cout << "wptr is still valid" << std::endl; } else { std::cout << "wptr is expired" << std::endl; } // lock() will now vend nullptr since we don't have a valid object sptr = wptr.lock(); std::cout << "sptr@" << sptr.get() << std::endl; // We use the factory and get a valid shared ptr out auto SharedThing = SharedThing::create("Thing 1"); std::cout << "Created SharedThing: " << SharedThing->name() << std::endl; // Now we can actually get instances of Thing 1 auto t = SharedThing->getSharedThing(); std::cout << "t points to: " << t->name() << std::endl; // Yay templates! different constructors will work auto SharedThing2 = SharedThing::create(); std::cout << "Thanks to perfect-forwarding, we also created: " << SharedThing2->name() << std::endl; return 0; } #ifdef __TM4C123GH6PM__ namespace std { ios_base::Init::Init() {} ios_base::Init::~Init() {} } // namespace std #include <Arduino.h> void setup() { // initialize LED digital pin as an output. pinMode(RED_LED, OUTPUT); } void loop() { // turn the LED on (HIGH is the voltage level) digitalWrite(RED_LED, HIGH); // wait for a second delay(1000); // turn the LED off by making the voltage LOW digitalWrite(RED_LED, LOW); // wait for a second delay(1000); } #else class B { protected: class Token {}; public: explicit B(Token) { /* ... */ } // create an imperfectly initialized object virtual void f() = 0; template <class T> static shared_ptr<T> create() // interface for creating shared objects { auto p = make_shared<T>(typename T::Token{}); p->post_initialize(); return p; } protected: virtual void post_initialize() // called right after construction { /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe }; class D : public B { // some derived class protected: class Token {}; public: explicit D(Token) : B{B::Token{}} {} void f() override{/* ... */}; protected: template <class T> friend shared_ptr<T> B::create(); }; int sharedptr_main() { using std::shared_ptr; shared_ptr<B> p = B::create<D>(); // creating a D object cppmain(); return 0; } #endif // PART_TM4C123GH6PM
#include "stdafx.h" #include "class.h" Data::Data(){} Data::Data(string make, string model, int body_type, int fuel, int transmission, int engine_size, int year, int value) { m_make = make; m_model = model; m_body_type = body_type; m_fuel = fuel; m_transmission = transmission; m_engine_size = engine_size; m_year = year; m_value = value; } string Data::convert_for_save(string mk, string md, int bt, int fu, int tr, int eng, int year, int val) { string text; replacing_space(mk); replacing_space(md); text.append(mk); text.append(" "); text.append(md); text.append(" "); text += to_string(bt); text.append(" "); text += to_string(fu); text.append(" "); text += to_string(tr); text.append(" "); text += to_string(eng); text.append(" "); text += to_string(year); text.append(" "); text += to_string(val); return text; } string Data::replacing_space(string &text) { for (unsigned int i = 0; i <= text.size(); i++) if (text[i] == ' ') text.replace(i, 1, "_"); return text; } void Data::save_to_file(string name) { fstream save(name, ios::out | ios::app); save << convert_for_save(m_make, m_model, m_body_type, m_fuel, m_transmission, m_engine_size, m_year, m_value); save << endl; save.close(); } void Data::browsing() { cout << "Marka: " << "\t\t\t" << m_make << endl; cout << "Model: " <<"\t\t\t"<< m_model << endl; cout << "Typ nadwodzia: " << "\t\t" << body_type(m_body_type)<< endl; cout << "Rodzaj skrzyni biegow: "<<"\t"; if (m_transmission == 1) cout << "Manualna" << endl; else cout << "Automatyczna" << endl; cout << "Rodzaj paliwa: " << "\t\t"<< fuel(m_fuel) << endl; cout << "Pojemnosc silnika: " <<"\t"<< m_engine_size <<" cm^3"<< endl; cout << "Rok produkcji: " <<"\t\t"<< m_year <<" rok"<< endl; cout << "Wartosc: " << "\t\t" << m_value << " zl" << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl; cout << "^-strzalka w gore = poprzedni v-strzalka w dol = nastepny" << endl; cout << "ESC = wyjscie DELETE = usun wybrany element" << endl; cout << "F1 = zapisz F3 = aktualizacja danych"; } void Data::browsing_wfilter() { cout << "Marka: " << "\t\t\t" << m_make << endl; cout << "Model: " << "\t\t\t" << m_model << endl; cout << "Typ nadwodzia: " << "\t\t" << body_type(m_body_type) << endl; cout << "Rodzaj skrzyni biegow: " << "\t"; if (m_transmission == 1) cout << "Manualna" << endl; else cout << "Automatyczna" << endl; cout << "Rodzaj paliwa: " << "\t\t" << fuel(m_fuel) << endl; cout << "Pojemnosc silnika: " << "\t" << m_engine_size << " cm^3" << endl; cout << "Rok produkcji: " << "\t\t" << m_year << " rok" << endl; cout << "Wartosc: " << "\t\t" << m_value << " zl" << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl << endl; cout << "^-strzalka w gore = poprzedni v-strzalka w dol = nastepny" << endl; cout << "ESC = wyjscie"; } string Data::body_type(int nr) { string one = "Hatchback"; string two = "Sedan"; string three = "Kombi"; string four= "Kabriolet"; string five = "Coupe"; string six = "SUV"; string seven = "Terenowy"; if (nr == 1) return one; else if (nr == 2) return two; else if (nr == 3) return three; else if (nr == 4) return four; else if (nr == 5) return five; else if (nr == 6) return six; else if (nr == 7) return seven; } string Data::fuel(int nr) { string one = "Benzyna"; string two = "Diesel"; string three = "LPG"; string four = "Elektryczny"; string five = "Hybryda"; if (nr == 1) return one; else if (nr == 2) return two; else if (nr == 3) return three; else if (nr == 4) return four; else if (nr == 5) return five; } bool compare_by_year(const Data & lhs, const Data &rhs) { return lhs.m_year < rhs.m_year; } bool compare_by_value(const Data &lhs, const Data &rhs) { return lhs.m_value < rhs.m_value; } bool compare_by_eng(const Data &lhs, const Data &rhs) { return lhs.m_engine_size < rhs.m_engine_size; } bool compare_by_make(const Data &lhs, const Data &rhs) { return lhs.m_make < rhs.m_make; } bool compare_by_model(const Data &lhs, const Data &rhs) { return lhs.m_model < rhs.m_model; } string Data::get_make() { return m_make; } string Data::get_model() { return m_model; } int Data::get_body() { return m_body_type; } int Data::get_fuel() { return m_fuel; } int Data::get_transmission() { return m_transmission; } int Data::get_engine() { return m_engine_size; } int Data::get_year() { return m_year; } int Data::get_value() { return m_value; } void Data::set_make(string e_make) { m_make = e_make; } void Data::set_model(string e_model) { m_model = e_model; } void Data::set_body_type(int nr) { m_body_type = nr; } void Data::set_fuel(int nr) { m_fuel = nr; } void Data::set_transmission(int nr) { m_transmission = nr; } void Data::set_engine_size(int nr) { m_engine_size = nr; } void Data::set_year(int nr) { m_year = nr; } void Data::set_value(int nr) { m_value = nr; }
#include <cstdio> #include <cstring> int main() { int num[20]; int numToCnt[11]; int maxi; while (scanf("%d", &num[0]) != EOF) { memset(numToCnt, 0, sizeof(numToCnt)); for (int i = 1; i < 20; i++) scanf("%d", &num[i]); for (int i = 0; i < 20; i++) numToCnt[num[i]]++; maxi = 0; for (int i = 0; i < 11; i++) if (numToCnt[i] > numToCnt[maxi]) maxi = i; printf("%d\n", maxi); } }
#include "WrapperClass.h" Napi::FunctionReference WrapperClass::constructor; WrapperClass::WrapperClass(const Napi::CallbackInfo& info) : Napi::ObjectWrap<WrapperClass>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int length = info.Length(); if (length != 1 || !info[0].IsNumber()) { Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException(); } Napi::Number value = info[0].As<Napi::Number>(); this->actualClass_ = new ActualClass(value.DoubleValue()); } Napi::Value WrapperClass::GetValue(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); double num = this->actualClass_->getValue(); return Napi::Number::New(env, num); } Napi::Value WrapperClass::Add(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); if ( info.Length() != 1 || !info[0].IsNumber()) { Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException(); } Napi::Number toAdd = info[0].As<Napi::Number>(); double answer = this->actualClass_->add(toAdd.DoubleValue()); return Napi::Number::New(info.Env(), answer); } Napi::Object WrapperClass::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "WrapperClass", { InstanceMethod("add", &WrapperClass::Add), InstanceMethod("getValue", &WrapperClass::GetValue), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set("WrapperClass", func); return exports; }
#include <bits/stdc++.h> using namespace std; // multiple states // buy[i] = max(buy[i - 1], sell[i - 2] - prices[i]); // sell[i] = max(sell[i - 1], buy[i - 1] + prices[i]); class Solution { public: int maxProfit(vector<int> &prices) { int ssize = prices.size(); if (ssize <= 1) return 0; vector<int> buy(ssize, 0); vector<int> sell(ssize, 0); buy[0] = -prices[0]; buy[1] = max(-prices[0], -prices[1]); sell[0] = 0; sell[1] = max(0, prices[1] - prices[0]); for (int i = 2; i < ssize; i++) { buy[i] = max(buy[i - 1], sell[i - 2] - prices[i]); sell[i] = max(sell[i - 1], buy[i - 1] + prices[i]); } return max(buy[ssize - 1], sell[ssize - 1]); } };
#include<bits/stdc++.h> using namespace std; void solve(vector<long long>& arr,int n,int m,long long& max_value,int& output,int index,int cur,int cur_str) { if(cur <= m) { if( cur> max_value) { max_value = cur; output = cur_str; } } if(index==n) { return ; } //include int temp = cur_str; cur_str = cur_str | (1<<index); solve(arr,n,m,max_value,output,index+1,cur+arr[index],cur_str); solve(arr,n,m,max_value,output,index+1,cur,temp); return ; } int main() { freopen("first_input.txt","r",stdin); freopen("first_output.txt","w",stdout); int t; cin >> t; while(t--) { long long n,m; cin >> n >> m; vector<long long> arr(n); for(int i=0;i<n;i++) { cin >> arr[i]; } long long max_value = INT_MIN; int output = 0; solve(arr,n,m,max_value,output,0,0,0); cout << max_value << endl; int cur = 1; for(int i=0;i<n;i++) { if((output&(1<<i)) != 0) { cout << i << " "; } } } return 0; }
#include<bits/stdc++.h> using namespace std; struct node { int data; node* left; node* right; node(int val) { data=val; left=NULL; right=NULL; } }; int sumAtK(node* root, int k) { if(root==NULL) //if root is null then return { return -1; } int level=0,sum=0; queue<node*> q; //creating a queue with node type(it will hold pointers) q.push(root); //inserting root in queue q.push(NULL); //inserting null, because it signifies that first level is traversed while(!q.empty()) //while queue is not empty perform following operations { node * n = q.front(); //create a node which will hold value of front of queue q.pop(); //pop the front of the queue if(n!=NULL) //check if the node is null or not { if(level==k) //if not we have reached teh desired level { sum+=n->data; //if yes then add its value to sum variable } if(n->left) //if the node has left subtree {q.push(n->left);} //push it to the queue if(n->right) //if the node has right subtree {q.push(n->right);} //push it to the queue } else if(!q.empty()) //if node is null then check if the queue is empty or not { q.push(NULL); //if not then add a null at end of queue. It signifies that traversal of one level is done and in //next iteration traversal of next level will begin. } } return sum; } int main() { //creating a tree node* root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left=new node(4); root->left->right=new node(5); root->right->left = new node(6); root->right->right = new node(7); cout<<sumAtK(root,2)<<endl; }
#include "Channel.h" #include <sys/epoll.h> #include "Logger.h" #include "EventLoop.h" USE_NAMESPACE constexpr int NoneEvent = 0; constexpr int ReadEvent = EPOLLIN | EPOLLPRI; constexpr int WriteEvent = EPOLLOUT; Channel::Channel(EventLoop& loop, int fd) : loop_(loop), fd_(fd), event_(0), actionEvents_(0), eventHandling_(false) {} void Channel::enableReading() { event_ |= ReadEvent; update(); } void Channel::enableWriting() { event_ |= WriteEvent; update(); } void Channel::enableReadAndWrite() { event_ |= WriteEvent; event_ |= ReadEvent; update(); } void Channel::disableReading() { event_ &= ~ReadEvent; update(); } void Channel::disableWriting() { event_ &= ~WriteEvent; update(); } void Channel::disableAll() { event_ = NoneEvent; update(); } bool Channel::isReading() const { return actionEvents_ & ReadEvent; } bool Channel::isWriting() const { return actionEvents_ & WriteEvent; } void Channel::remove() { loop_.removeChannel(*this); } void Channel::handleEvent() { eventHandling_ = true; LOG_TRACE << eventToString(fd_, actionEvents_); // connection close by peer if ((actionEvents_ & EPOLLHUP) && !(actionEvents_ & EPOLLIN)) if (closeCallback_) closeCallback_(); if (actionEvents_ & EPOLLERR) if (errorCallback_) errorCallback_(); if (actionEvents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) if (readCallback_) readCallback_(); if (actionEvents_ & EPOLLOUT) if (writeCallback_) writeCallback_(); eventHandling_ = false; } std::string Channel::eventToString(int fd, int event) { std::string str = "fd = " + std::to_string(fd) + ", event = "; if (event & EPOLLIN) str += "EPOLLIN "; if (event & EPOLLOUT) str += "EPOLLOUT "; if (event & EPOLLERR) str += "EPOLLERR "; if (event & EPOLLPRI) str += "EPOLLPRI "; if (event & EPOLLHUP) str += "EPOLLHUP "; if (event & EPOLLRDHUP) str += "EPOLLRDHUP "; return str; } void Channel::update() { if (loop_.hasChannel(*this)) { loop_.updateChannel(*this); } else loop_.insertChannel(*this); }
// This file has been generated by Py++. #ifndef FontIterator_hpp__pyplusplus_wrapper #define FontIterator_hpp__pyplusplus_wrapper void register_FontIterator_class(); #endif//FontIterator_hpp__pyplusplus_wrapper
#include <Arduino.h> #include "Can485DisplayHelper.h" #define BLOCK 255 void setup() { DisplayInit(); } void loop() { clearDisplay(); delay(200); setCursorPosition(1,1); writeToDisplay("Hello World!"); delay(500); clearDisplay(); delay(200); setCursorPosition(2,1); if(false) { for(int i = 0; i < 6; i++) { writeToDisplay(i); delay(50); } } if(true) { writeToDisplay(BLOCK); writeToDisplay(BLOCK); } delay(2000); } void printMockGauges() { setCursorPosition(1,1); writeToDisplay("AFR 13.5"); writeToDisplay(BLOCK); writeToDisplay(BLOCK); writeToDisplay(BLOCK); setCursorPosition(2,1); writeToDisplay("TGT 14.7"); writeToDisplay(BLOCK); writeToDisplay(BLOCK); writeToDisplay(BLOCK); writeToDisplay(BLOCK); }
/************************************************************* * > File Name : P2723.cpp * > Author : Tony * > Created Time : 2019/05/16 12:41:08 **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxk = 110; const int maxn = 100010; long long k, n, a[maxk], i, t, s[maxn], b[maxk]; int main() { scanf("%lld %lld", &k, &n); for (long long i = 1; i <= k; ++i) { scanf("%lld", &a[i]); } s[0] = 1; for (long long i = 1; i <= n; ++i) { long long minn = 0x3f3f3f3f; for (long long j = 1; j <= k; ++j) { while (a[j] * s[b[j]] <= s[i - 1]) { b[j]++; } if (a[j] * s[b[j]] < minn) { minn = a[j] * s[b[j]]; } } s[i] = minn; } printf("%lld\n", s[n]); return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <set> #include <algorithm> #include <chrono> using namespace std; int main() { int n; cin >> n; vector<unordered_set<int>> subset(n); unordered_map<int, int> position, run_id_position; vector<unordered_set<int>> v; vector<int> f(n); int m = 0; vector<int> line_numbers, run_id; for (int i = 0; i < n; i++) { int cardinality, id; cin >> cardinality >> id; if (run_id_position.find(id) == run_id_position.end()) { run_id_position[id] = i; run_id.push_back(id); } for (int j = 0; j < cardinality; j++) { int line_num; cin >> line_num; if (position.find(line_num) == position.end()) { position[line_num] = m++; line_numbers.push_back(line_num); unordered_set<int> tmp; v.push_back(tmp); } subset[i].insert(position[line_num]); v[position[line_num]].insert(i); } } unsigned int cnt = (1u << n); int ans = n; for (unsigned int i = 0; i < cnt; i++) { unordered_set<int> s; int cur_ans = 0; for (int j = 0; j < n; j++) { if ((i & (1u << j)) != 0) { cout << '1'; for (auto it: subset[j]) { s.insert(it); } cur_ans++; } else { cout << '0'; } } cout << ' ' << cur_ans; cout << endl; if (s.size() == m) { ans = min(ans, cur_ans); } } cout << ans << endl; }
#include <iostream> #include <string> #include "itkImage.h" #include "itkImageFileReader.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkGradientImageFilter.h" #include "itkPoint.h" #include <sstream> #include <fstream> #include "itkFixedArray.h" #include "utils.h" #include "vnl/vnl_vector_fixed.h" #include "tinyxml.h" #include <vector> int main(int argc, char *argv[]) { if (argc != 2) { std::cout << "-------------------------------" << std::endl; std::cout << "ComputeMeanNormals " << std::endl; std::cout << "-------------------------------" << std::endl; std::cout << "Compute mean normals using spherical coordinates for given normals for a set of shapes " << std::endl; std::cout << "It uses a parameter file with the following tags" << std::endl; std::cout << "\t - normals: a list of files containing normals at a set of points on each shape (output files from ProbeNormals)" << std::endl; std::cout << "\t - pointsCount: number of points in every shape file" << std::endl; std::cout << "\t - outFileName: full filename (with path) to save resulting file (default: mean.normals.txt)" << std::endl; std::cout << "Usage: " << argv[0] << " parameter_file" << std::endl; return EXIT_FAILURE; } TiXmlDocument doc(argv[1]); bool loadOkay = doc.LoadFile(); std::vector< std::string > nrmFilename; std::string outFilename; std::vector< std::vector< double > > thetas ; std::vector< std::vector< double > > phis; int numPoints; if (loadOkay) { TiXmlHandle docHandle( &doc ); TiXmlElement *elem; std::istringstream inputsBuffer; std::string tmpString; elem = docHandle.FirstChild( "normals" ).Element(); if (!elem) { std::cerr << "No normal files have been specified" << std::endl; throw 1; } else { nrmFilename.clear(); inputsBuffer.str(elem->GetText()); while (inputsBuffer >> tmpString) { nrmFilename.push_back(tmpString); } inputsBuffer.clear(); inputsBuffer.str(""); } elem = docHandle.FirstChild("pointsCount").Element(); if(!elem) { std::cerr << "Number of points not set!!!!!!" << std::endl; throw 1; } else { numPoints = atoi(elem->GetText()); } elem = docHandle.FirstChild("outFileName").Element(); if(!elem) { std::cerr << "No out file name.. default name mean.normals.txt being set" << std::endl; outFilename = "mean.normals.txt"; } else { inputsBuffer.str(elem->GetText()); inputsBuffer >> outFilename; inputsBuffer.clear(); inputsBuffer.str(""); } } else { std::cerr << "Failed at loading parameter file: " << argv[1] <<std::endl; throw 1; } int numFiles = nrmFilename.size(); thetas.resize(numPoints); phis.resize(numPoints); for (int i = 0; i < numPoints; i++) { thetas[i].resize(numFiles); phis[i].resize(numFiles); } for (int i = 0; i < numFiles; i++) { std::ifstream normalFile(nrmFilename[i].c_str()); if (!normalFile) { std::cout << "normal file does not exist... " << normalFile << std::endl; return EXIT_FAILURE; } else { int j = 0; while(normalFile) { double in[3]; normalFile >> in[0]; if (!normalFile) break; normalFile >> in[1]; normalFile >> in[2]; double out[3]; utils::cartesian2spherical(in, out); phis[j][i] = out[1]; thetas[j][i] = out[2]; j++; } } normalFile.close(); } std::ofstream outfile(outFilename.c_str()); for (int i = 0; i < numPoints; i++) { double avgNormal_sph[3]; double avgNormal_cart[3]; avgNormal_sph[0] = 1; avgNormal_sph[1] = utils::averageThetaArc(phis[i]); avgNormal_sph[2] = utils::averageThetaArc(thetas[i]); utils::spherical2cartesian(avgNormal_sph, avgNormal_cart); outfile << avgNormal_cart[0] << " " << avgNormal_cart[1] << " " << avgNormal_cart[2] << std::endl; } outfile.close(); return 0; }
//----------------------------------------------------------------------------- // Perimeter Map Compiler // Copyright (c) 2005, Don Reba // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // • Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // • Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // • Neither the name of Don Reba nor the names of his contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #pragma once #include "error handler.h" #include "task resources.h" #include <utility> struct TextureAllocation; struct SimpleVertex; //------------------------------------------------------------ // some functions used by the Tasks, but also useful to others //------------------------------------------------------------ namespace TaskCommon { //-------- // file IO //-------- DWORD LoadFile(const LPCTSTR name, BYTE *&pBuffer, ErrorHandler &error_handler); bool SaveMemToFile(LPCTSTR path, const BYTE *buffer, DWORD size, ErrorHandler &error_handler); void SavePalette(Texture &texture, LPCTSTR path, ErrorHandler &error_handler); void SaveSPG( MapInfo &map_info, LPCTSTR path, LPCTSTR folder_name, const bool survival, ErrorHandler &error_handler); void SaveSPG2( MapInfo &map_info, LPCTSTR path, LPCTSTR folder_name, const bool survival, ErrorHandler &error_handler); void SaveSPH( LPCTSTR path, LPCTSTR folder_name, const bool survival, ErrorHandler &error_handler); bool SaveThumb( const Heightmap &heightmap, const Lightmap &lightmap, const Texture &texture, LPCTSTR path, SIZE size, ErrorHandler &error_handler); void SaveVMP( const Heightmap &heightmap, const Texture &texture, const ZeroLayer *zero_layer, LPCTSTR path, ErrorHandler &error_handler); void SaveVMP8( const Heightmap &heightmap, const Texture &texture, const ZeroLayer *zero_layer, LPCTSTR path, ErrorHandler &error_handler); void SaveVMP16( const Heightmap &heightmap, const Texture &texture, const ZeroLayer *zero_layer, LPCTSTR path, ErrorHandler &error_handler); //----------------------------------- // "incredible math" (Lithium Flower) //----------------------------------- COLORREF AverageColour (const Texture &texture, const Heightmap &heightmap); COLORREF AverageColour8 (const Texture &texture, const Heightmap &heightmap); COLORREF AverageColour16(const Texture &texture, const Heightmap &heightmap); float AverageHeight (const Heightmap &heightmap); float AverageHeight8 (const Heightmap &heightmap); float AverageHeight16(const Heightmap &heightmap); DWORD CalculateChecksum(BYTE *data, size_t size, DWORD seed); void CreateTextures( const Texture &texture, TextureAllocation &allocation, const Lightmap &lightmap, bool enable_lighting); void CreateTextures( const Hardness &hardness, TextureAllocation &allocation, const Lightmap &lightmap, bool enable_lighting); void CreateTextures( const ZeroLayer &zero_layer, TextureAllocation &allocation, const Lightmap &lightmap, bool enable_lighting); float Flatness(float h1, float h2, float v1, float v2, float c, float r); void ReplaceSubstringSeq( LPCTSTR str, size_t str_length, const vector<std::pair<tstring, tstring> > &seq, tstring &result); void Triangulate( const Heightmap &heightmap, vector<SimpleVertex> &vertices, float mesh_threshold); //------ // other //------ bool RegisterMap(LPCTSTR map_name, DWORD checksum, ErrorHandler &error_handler); } //------------------------- // template implementations //------------------------- namespace TaskCommon { template<typename HMType> COLORREF AverageColour(const Texture &texture, const HMType &heightmap) { const BYTE *texture_iter; const BYTE *heightmap_iter; const size_t num_colors(256); int color_count[num_colors]; const int *color_iter; uint half_size(0); uint sum; LONG r, c; // row, column // count the number of non-null pixels of the heightmap heightmap_iter = heightmap.data_; for (r = 0; r != texture.size_.cy; ++r) { for (c = 0; c != texture.size_.cx; ++c) if (0 != *heightmap_iter++) ++half_size; ++heightmap_iter; } half_size /= 2; // count the number of occurences of each value of blue ZeroMemory(color_count, num_colors * sizeof(int)); heightmap_iter = heightmap.data_; texture_iter = texture.indices_; for (r = 0; r != texture.size_.cy; ++r) { for (c = 0; c != texture.size_.cx; ++c) { if (0 != *heightmap_iter) ++color_count[GetBValue(texture.palette_[*texture_iter])]; ++heightmap_iter; ++texture_iter; } ++heightmap_iter; } // find the median blue BYTE median_b; sum = 0; color_iter = color_count; do { _ASSERTE(color_iter != color_count + num_colors); sum += *color_iter; ++color_iter; } while (sum < half_size); --color_iter; median_b = static_cast<BYTE>(color_iter - color_count); // count the number of occurences of each value of green ZeroMemory(color_count, num_colors * sizeof(int)); heightmap_iter = heightmap.data_; texture_iter = texture.indices_; for (r = 0; r != texture.size_.cy; ++r) { for (c = 0; c != texture.size_.cx; ++c) { if (0 != *heightmap_iter) ++color_count[GetGValue(texture.palette_[*texture_iter])]; ++heightmap_iter; ++texture_iter; } ++heightmap_iter; } // find the median green BYTE median_g; sum = 0; color_iter = color_count; do { _ASSERTE(color_iter != color_count + num_colors); sum += *color_iter; ++color_iter; } while (sum < half_size); --color_iter; median_g = static_cast<BYTE>(color_iter - color_count); // count the number of occurences of each value of green ZeroMemory(color_count, num_colors * sizeof(int)); heightmap_iter = heightmap.data_; texture_iter = texture.indices_; for (r = 0; r != texture.size_.cy; ++r) { for (c = 0; c != texture.size_.cx; ++c) { if (0 != *heightmap_iter) ++color_count[GetRValue(texture.palette_[*texture_iter])]; ++heightmap_iter; ++texture_iter; } ++heightmap_iter; } // find the median red BYTE median_r; sum = 0; color_iter = color_count; do { _ASSERTE(color_iter != color_count + num_colors); sum += *color_iter; ++color_iter; } while (sum < half_size); --color_iter; median_r = static_cast<BYTE>(color_iter - color_count); return RGB(median_r, median_g, median_b); } }
/* * SPDX-FileCopyrightText: 2020 Rolf Eike Beer <eike@sf-mail.de> * * SPDX-License-Identifier: GPL-3.0-or-later */ #include "icon.h" #include <algorithm> #include <array> #include <cstring> #include <filesystem> #include <memory> #include <QDebug> #include <QLabel> #include <QPainter> #include <QString> #include <QStringBuilder> #include <QSvgRenderer> #include <string> #include <sys/stat.h> #include <unordered_map> #include "osm2go_annotations.h" #include <osm2go_cpp.h> #include "osm2go_platform.h" #include "osm2go_platform_qt.h" namespace { class icon_buffer_item : public icon_item { public: icon_buffer_item() = delete; icon_buffer_item(const icon_buffer_item &) = delete; icon_buffer_item(icon_buffer_item &&) = delete; inline icon_buffer_item(const QPixmap &p, std::unique_ptr<QSvgRenderer> &&r) : icon_item(), buf(p), renderer(std::move(r)) { assert(!!buf); } icon_buffer_item &operator=(const icon_buffer_item &) = delete; icon_buffer_item &operator=(icon_buffer_item &&) = delete; ~icon_buffer_item() = default; QPixmap buf; const std::unique_ptr<QSvgRenderer> renderer; int use = 1; }; class icon_buffer : public icon_t { public: icon_buffer() = default; icon_buffer(const icon_buffer &) = delete; icon_buffer(icon_buffer &&) = delete; icon_buffer &operator=(const icon_buffer &) = delete; icon_buffer &operator=(icon_buffer &&) = delete; ~icon_buffer() = default; typedef std::unordered_map<std::string, std::unique_ptr<icon_buffer_item>> BufferMap; BufferMap entries; }; QString icon_file_exists(const std::string &file) { const std::array<QString, 4> icon_exts = { { QStringLiteral(".svg"), QStringLiteral(".png"), QStringLiteral(".gif"), QStringLiteral(".jpg") } }; QString ret; // absolute filenames are not mangled if(unlikely(file[0] == '/')) { if(likely(std::filesystem::is_regular_file(file))) ret = QString::fromStdString(file); return ret; } const int wpos = QStringLiteral("icons/").length() + file.size(); QString iname = QStringLiteral("icons/") % QString::fromStdString(file) % icon_exts[0]; for (auto &&ext : icon_exts) { const int longEnough = 32; // must be larger than any entry in icon_exts iname.replace(wpos, longEnough, ext); ret = osm2go_platform::find_file(iname); if (!ret.isEmpty()) break; } return ret; } } // namespace icon_item * icon_t::load(const std::string &sname, int limit) { assert(!sname.empty()); icon_buffer::BufferMap &entries = static_cast<icon_buffer *>(this)->entries; /* check if icon list already contains an icon of that name */ const auto it = entries.find(sname); if(it != entries.end()) { it->second->use++; return it->second.get(); } const QString fullname = icon_file_exists(sname); if(!fullname.isEmpty()) { QPixmap pix; if(pix.load(fullname)) { std::unique_ptr<QSvgRenderer> rnd; if(fullname.endsWith(QLatin1String(".svg"))) { rnd = std::make_unique<QSvgRenderer>(fullname); if(!rnd->isValid()) rnd.reset(); } if(limit > 0) pix = pix.scaledToWidth(limit); qDebug() << "Successfully loaded icon" << fullname << "to" << pix << rnd.get() << limit; icon_buffer_item *ret = new icon_buffer_item(pix, std::move(rnd)); entries[sname] = std::unique_ptr<icon_buffer_item>(ret); return ret; } } qDebug() << "Icon not found:" << QString::fromStdString(sname); return nullptr; } int icon_item::maxDimension() const { const auto bi = static_cast<const icon_buffer_item *>(this); if (bi->renderer == nullptr) { const QPixmap &buf = bi->buf; return std::max(buf.height(), buf.width()); } else { auto r = bi->renderer->viewBox(); return std::max(r.height(), r.width()); } } void icon_t::icon_free(icon_item *buf) { // check if icon list already contains an icon of that name icon_buffer::BufferMap &entries = static_cast<icon_buffer *>(this)->entries; const auto itEnd = entries.end(); auto it = std::find_if(entries.begin(), itEnd, [buf](auto &&p) { return p.second.get() == buf; }); assert(it != itEnd); it->second->use--; if(it->second->use == 0) entries.erase(it); } icon_t &icon_t::instance() { static icon_buffer icons; return icons; } QPixmap osm2go_platform::icon_pixmap(icon_item *icon) { return static_cast<icon_buffer_item *>(icon)->buf; } QSvgRenderer * osm2go_platform::icon_renderer(const icon_item *icon) { return static_cast<const icon_buffer_item *>(icon)->renderer.get(); }
/** * * @file SerialDeviceSelector.cpp * @author Naoki Takahashi * **/ #include "SerialDeviceSelector.hpp" #include "Device/Actuator/ServoMotor/SerialServoMotor.hpp" #include "Device/ControlBoard/SerialControlBoard.hpp" #include "Device/Sensor/IMU/InertialMeasurementUnit.hpp" #include "Device/Actuator/ServoMotor/MX28.hpp" #include "Device/Actuator/ServoMotor/B3MSC1170A.hpp" #include "Device/ControlBoard/CM730.hpp" #include "Device/Sensor/IMU/VMU931.hpp" namespace IO { template <typename Base> SerialDeviceSelector<Base>::SerialDeviceSelector(RobotStatus::InformationPtr &robot_status_information_ptr) { robo_info = robot_status_information_ptr; default_register(); } template <typename Base> SerialDeviceSelector<Base>::~SerialDeviceSelector() { } template <> void SerialDeviceSelector<Device::Actuator::ServoMotor::SerialServoMotor>::default_register() { this->register_object( { Device::Actuator::ServoMotor::MX28::get_key(), std::make_unique<Device::Actuator::ServoMotor::MX28>(robo_info), } ); this->register_object( { Device::Actuator::ServoMotor::B3MSC1170A::get_key(), std::make_unique<Device::Actuator::ServoMotor::B3MSC1170A>(robo_info), } ); } template <> void SerialDeviceSelector<Device::ControlBoard::SerialControlBoard>::default_register() { this->register_object( { Device::ControlBoard::CM730::get_key(), std::make_unique<Device::ControlBoard::CM730>(robo_info), } ); } template <> void SerialDeviceSelector<Device::Sensor::IMU::InertialMeasurementUnit>::default_register() { this->register_object( { Device::Sensor::IMU::VMU931::get_key(), std::make_unique<Device::Sensor::IMU::VMU931>(robo_info) } ); } template class SerialDeviceSelector<Device::Actuator::ServoMotor::SerialServoMotor>; template class SerialDeviceSelector<Device::ControlBoard::SerialControlBoard>; template class SerialDeviceSelector<Device::Sensor::IMU::InertialMeasurementUnit>; }
/* * Copyright (C) 2019 wuuhii. All rights reserved. * * The file is encoding with utf-8 (with BOM). It is a part of QtSwissArmyKnife * project. The project is a open source project, you can get the source from: * https://github.com/wuuhii/QtSwissArmyKnife * https://gitee.com/wuuhii/QtSwissArmyKnife * * If you want to know more about the project, please join our QQ group(952218522). * In addition, the email address of the project author is wuuhii@outlook.com. */ #ifndef SAKUPDATEMANAGER_HH #define SAKUPDATEMANAGER_HH #include <QTimer> #include <QLabel> #include <QDialog> #include <QGroupBox> #include <QCheckBox> #include <QListWidget> #include <QPushButton> #include <QProgressBar> #include <QTextBrowser> #include <QNetworkReply> #include <QNetworkAccessManager> namespace Ui { class SAKUpdateManager; } class SAKUpdateManager:public QDialog { Q_OBJECT public: SAKUpdateManager(QWidget *parent = nullptr); ~SAKUpdateManager(); void checkForUpdate(); bool enableAutoCheckedForUpdate(); private: Ui::SAKUpdateManager *ui; QLabel *currentVersionLabel; QLabel *newVersionLabel; QLabel *updateProgressLabel; QProgressBar *updateProgressBar; QLabel *noNewVersionTipLabel; QGroupBox *newVersionCommentsGroupBox; QTextBrowser *newVersionCommentsTextBrowser; QListWidget *downloadListListWidget; QCheckBox *autoCheckForUpdateCheckBox; QPushButton *visitWebPushButton; QPushButton *checkForUpdatePushButton; QLabel *infoLabel; private slots: void on_autoCheckForUpdateCheckBox_clicked(); void on_visitWebPushButton_clicked(); void on_checkForUpdatePushButton_clicked(); private: struct UpdateInfo{ bool isValid; // 是否可用 QString errorString; // 错误信息 QString htmlUrl; // 发布页面地址 QString name; // 最新版本号 QStringList browserDownloadUrl; // 下载链接 QString body; // 发布描述 QString tarballUrl; // 源码包(tar.tz) QString zipballUrl; // 源码包(zip) }updateInfo; QTimer clearInfoTimer; QNetworkAccessManager networkAccessManager; QNetworkReply *networkReply; private: void outputInfo(QString info, bool isError = false); void clearInfo(); void checkForUpdateFinished(); UpdateInfo extractUpdateInfo(QByteArray jsonObjectData); QStringList extractBrowserDownloadUrl(QJsonArray jsonArray); bool isNewVersion(QString remoteVersion); void setupDownloadList(UpdateInfo info); void clearDownloadList(); }; #endif
#include "GPUOCLLayer.h" #include "crandom.h" #include "MemoryStorageCPU.h" #include "MemoryStorageOCL.h" void GPUOCLLayer::CreateBuffersGeom(InputGeom a_input, cl_mem_flags a_flags) { } void GPUOCLLayer::CreateBuffersBVH(InputGeomBVH a_input, cl_mem_flags a_flags) { } //m_memoryTaken[MEM_TAKEN_GEOMETRY] = compressedNorm.size()*sizeof(float)*5 + a_input.vertNum*sizeof(float2) + a_input.numIndices*sizeof(int); //// void GPUOCLLayer::Clear(CLEAR_FLAGS a_flags) { } void GPUOCLLayer::SetNamedBuffer(const char* a_name, void* a_data, size_t a_size) { cl_int ciErr1 = CL_SUCCESS; if (std::string(a_name) == "ao" && a_size == size_t(-1)) { m_rays.aoCompressed = clCreateBuffer(m_globals.ctx, CL_MEM_READ_WRITE, m_rays.MEGABLOCKSIZE, nullptr, &ciErr1); // byte buffer return; } if (std::string(a_name) == "ao2" && a_size == size_t(-1)) { m_rays.aoCompressed2 = clCreateBuffer(m_globals.ctx, CL_MEM_READ_WRITE, m_rays.MEGABLOCKSIZE, nullptr, &ciErr1); // byte buffer return; } auto p = m_scene.namedBuffers.find(a_name); if (p != m_scene.namedBuffers.end()) { clReleaseMemObject(p->second); p->second = 0; } m_scene.namedBuffers[a_name] = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a_size, a_data, &ciErr1); if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR((std::string("Error in clCreateBuffer, SetNamedBuffer, name = ") + a_name).c_str()); } IMemoryStorage* GPUOCLLayer::CreateMemStorage(uint64_t a_maxSizeInBytes, const char* a_name) { IMemoryStorage* pStorage = nullptr; cl_mem buff = 0; if (std::string(a_name) == "geom" || std::string(a_name) == "textures") { LinearStorageCPU* pCPUImpl = new LinearStorageCPU(); MemoryStorageOCL* pGPUImpl = new MemoryStorageOCL(m_globals.ctx, m_globals.cmdQueue); pStorage = new MemoryStorageBothCPUAndGPU(pCPUImpl, pGPUImpl); pStorage->Reserve(a_maxSizeInBytes); buff = pGPUImpl->GetOCLBuffer(); } else { MemoryStorageOCL* pGPUImpl = new MemoryStorageOCL(m_globals.ctx, m_globals.cmdQueue); pGPUImpl->Reserve(a_maxSizeInBytes); buff = pGPUImpl->GetOCLBuffer(); pStorage = pGPUImpl; } m_allMemStorages[a_name] = pStorage; if (std::string(a_name) == "textures") m_scene.storageTex = buff; else if (std::string(a_name) == "geom") m_scene.storageGeom = buff; else if (std::string(a_name) == "materials") m_scene.storageMat = buff; else if(std::string(a_name) == "pdfs") m_scene.storagePdfs = buff; else if(std::string(a_name) == "textures_aux") m_scene.storageTexAux = buff; return pStorage; } void GPUOCLLayer::SetAllBVH4(const ConvertionResult& a_convertedBVH, IBVHBuilder2* a_inBuilderAPI, int a_flags) { for (int i = 0; i < m_scene.bvhNumber; i++) { if (m_scene.bvhBuff[i] != nullptr) { clReleaseMemObject(m_scene.bvhBuff[i]); m_scene.bvhBuff [i] = nullptr; } if (m_scene.objListBuff[i] != nullptr) { clReleaseMemObject(m_scene.objListBuff[i]); m_scene.objListBuff[i] = nullptr; } if (m_scene.alphTstBuff[i] != nullptr) { clReleaseMemObject(m_scene.alphTstBuff[i]); m_scene.alphTstBuff[i] = nullptr; } } cl_int ciErr1 = CL_SUCCESS; m_memoryTaken[MEM_TAKEN_BVH] = 0; for (int i = 0; i < a_convertedBVH.treesNum; i++) { const size_t nodesSize = a_convertedBVH.nodesNum[i]*sizeof(BVHNode); const size_t primsSize = a_convertedBVH.trif4Num[i]*sizeof(float4); const size_t alphaSize = a_convertedBVH.triAfNum[i]*sizeof(uint2); m_memoryTaken[MEM_TAKEN_BVH] += (nodesSize + primsSize); if (a_convertedBVH.pTriangleAlpha[i]) m_memoryTaken[MEM_TAKEN_BVH] += alphaSize; m_scene.bvhBuff [i] = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, nodesSize, (void*)a_convertedBVH.pBVH[i], &ciErr1); m_scene.objListBuff[i] = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, primsSize, (void*)a_convertedBVH.pTriangleData[i], &ciErr1); if(a_convertedBVH.pTriangleAlpha[i] != nullptr) m_scene.alphTstBuff[i] = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, alphaSize, (void*)a_convertedBVH.pTriangleAlpha[i], &ciErr1); m_scene.bvhHaveInst[i] = (std::string(a_convertedBVH.bvhType[i]) != "triangle4v"); // or (bvhType == "object") m_bvhTrees[i].smoothOpacity = (a_flags & BVH_ENABLE_SMOOTH_OPACITY) != 0; } m_scene.bvhNumber = a_convertedBVH.treesNum; if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllBVH4 Error in clCreateBuffer"); } void GPUOCLLayer::SetAllInstMatrices(const float4x4* a_matrices, int32_t a_matrixNum) { if (a_matrices == nullptr || a_matrixNum == 0) { if (m_scene.matrices != nullptr) clReleaseMemObject(m_scene.matrices); m_scene.matrices = nullptr; m_scene.matricesSize = 0; return; } const size_t newSize = a_matrixNum * sizeof(float4x4); cl_int ciErr1 = CL_SUCCESS; if (m_scene.matrices == nullptr || m_scene.matricesSize < newSize) { if (m_scene.matrices != nullptr) clReleaseMemObject(m_scene.matrices); m_scene.matrices = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, newSize, (void*)a_matrices, &ciErr1); m_scene.matricesSize = newSize; } else { CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.matrices, CL_TRUE, 0, newSize, (void*)a_matrices, 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllInstMatrices: Error in clCreateBuffer / clEnqueueWriteBuffer"); m_scene.totalInstanceNum = a_matrixNum; } void GPUOCLLayer::SetAllInstLightInstId(const int32_t* a_lightInstIds, int32_t a_instNum) { if (a_instNum == 0 || a_lightInstIds == nullptr) { std::cerr << "WARNING: GPUOCLLayer::SetAllInstLightInstId, no lights!" << std::endl; m_scene.instLightInst = nullptr; m_scene.instLightInstSize = 0; return; } const size_t newSize = a_instNum * sizeof(int32_t); cl_int ciErr1 = CL_SUCCESS; if (m_scene.instLightInst == nullptr || m_scene.instLightInstSize < newSize) { if (m_scene.instLightInst != nullptr) clReleaseMemObject(m_scene.instLightInst); m_scene.instLightInst = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, newSize, (void*)a_lightInstIds, &ciErr1); m_scene.instLightInstSize = newSize; } else { CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.instLightInst, CL_TRUE, 0, newSize, (void*)a_lightInstIds, 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllInstLightInstId: Error in clCreateBuffer / clEnqueueWriteBuffer"); } void GPUOCLLayer::SetAllPODLights(PlainLight* a_lights2, size_t a_number) { Base::SetAllPODLights(a_lights2, a_number); } void GPUOCLLayer::SetAllRemapLists(const int* a_allLists, const int2* a_table, int a_allSize, int a_tableSize) { if (a_allSize == 0 || a_tableSize == 0 || a_allLists == nullptr || a_table == nullptr) { m_scene.remapLists = nullptr; m_scene.remapTable = nullptr; m_scene.remapListsSize = 0; m_scene.remapTableSize = 0; return; } cl_int ciErr1 = CL_SUCCESS; // (1) update all remap lists // if (m_scene.remapLists == nullptr || m_scene.remapListsSize < a_allSize) { if (m_scene.remapLists != nullptr) clReleaseMemObject(m_scene.remapLists); m_scene.remapLists = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a_allSize*sizeof(int), (void*)a_allLists, &ciErr1); m_scene.remapListsSize = a_allSize; } else { CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.remapLists, CL_TRUE, 0, a_allSize * sizeof(int), (void*)a_allLists, 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllInstLightInstId: Error in clCreateBuffer / clEnqueueWriteBuffer"); // (2) update remap table // if (m_scene.remapTable == nullptr || m_scene.remapTableSize < a_tableSize) { if (m_scene.remapTable != nullptr) clReleaseMemObject(m_scene.remapTable); m_scene.remapTable = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a_tableSize * sizeof(int2), (void*)a_table, &ciErr1); m_scene.remapTableSize = a_tableSize; } else { CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.remapTable, CL_TRUE, 0, a_tableSize * sizeof(int2), (void*)a_table, 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllInstLightInstId: Error in clCreateBuffer / clEnqueueWriteBuffer"); } void GPUOCLLayer::SetAllInstIdToRemapId(const int* a_allInstId, int a_instNum) { if (a_instNum == 0 || a_allInstId == nullptr) { m_scene.remapInst = nullptr; m_scene.remapInstSize = 0; return; } cl_int ciErr1 = CL_SUCCESS; if (m_scene.remapInst == nullptr || m_scene.remapInstSize < a_instNum) { if (m_scene.remapInst != nullptr) clReleaseMemObject(m_scene.remapInst); m_scene.remapInst = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a_instNum * sizeof(int), (void*)a_allInstId, &ciErr1); m_scene.remapInstSize = a_instNum; } else { CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.remapInst, CL_TRUE, 0, a_instNum * sizeof(int), (void*)a_allInstId, 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::SetAllInstLightInstId: Error in clCreateBuffer / clEnqueueWriteBuffer"); } void GPUOCLLayer::UpdateVarsOnGPU(const AllRenderVarialbes& a_inVars) { memcpy(m_globsBuffHeader.varsI, a_inVars.m_varsI, sizeof(int)*GMAXVARS); memcpy(m_globsBuffHeader.varsF, a_inVars.m_varsF, sizeof(float)*GMAXVARS); m_globsBuffHeader.g_flags = a_inVars.m_flags; CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.allGlobsData, CL_TRUE, 0, sizeof(EngineGlobals), &m_globsBuffHeader, 0, NULL, NULL)); // put m_globsBuffHeader to the beggining of the buffer } void GPUOCLLayer::PrepareEngineGlobals() { Base::PrepareEngineGlobals(); size_t totalBuffSize = m_cdataPrepared.size()*sizeof(int); cl_int ciErr1 = 0; if (m_scene.allGlobsData == 0) { m_scene.allGlobsData = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, totalBuffSize, &m_cdataPrepared[0], &ciErr1); // m_scene.allGlobsDataSize = totalBuffSize; } else { size_t newSize = sizeof(EngineGlobals); CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.allGlobsData, CL_FALSE, 0, newSize, &m_cdataPrepared[0], 0, NULL, NULL)); } if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::PrepareEngineGlobals: Error in clCreateBuffer / clEnqueueWriteBuffer"); } void GPUOCLLayer::PrepareEngineTables() { Base::PrepareEngineTables(); size_t totalBuffSize = m_cdataPrepared.size()*sizeof(int); if (m_scene.allGlobsDataSize < totalBuffSize) { cl_int ciErr1 = 0; clReleaseMemObject(m_scene.allGlobsData); m_scene.allGlobsData = clCreateBuffer(m_globals.ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, totalBuffSize, &m_cdataPrepared[0], &ciErr1); // if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::PrepareEngineTables: Error in clCreateBuffer"); } else CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.allGlobsData, CL_FALSE, 0, totalBuffSize, &m_cdataPrepared[0], 0, NULL, NULL)); } void GPUOCLLayer::UpdateConstants() { if (m_cdataPrepared.size() == 0) return; const size_t constantsSize = sizeof(EngineGlobals); int* pbuff = &m_cdataPrepared[0]; memcpy(pbuff, &m_globsBuffHeader, constantsSize); CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_scene.allGlobsData, CL_FALSE, 0, constantsSize, &m_cdataPrepared[0], 0, NULL, NULL)); } void GPUOCLLayer::SetAllFlagsAndVars(const AllRenderVarialbes& a_vars) { this->Base::SetAllFlagsAndVars(a_vars); UpdateConstants(); m_storeShadowInAlphaChannel = (a_vars.m_varsI[HRT_STORE_SHADOW_COLOR_W] == 1); } void GPUOCLLayer::CallNamedFunc(const char* a_name, const char* a_args) { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GPUOCLLayer::runTraceCPU(cl_mem a_rpos, cl_mem a_rdir, cl_mem a_hits, size_t a_size) { CHECK_CL(clFinish(m_globals.cmdQueue)); cl_int ciErr1 = 0; float4* rpos = (float4*) clEnqueueMapBuffer(m_globals.cmdQueue, a_rpos, CL_TRUE, CL_MAP_READ, 0, a_size*sizeof(float4), 0, 0, 0, &ciErr1); float4* rdir = (float4*) clEnqueueMapBuffer(m_globals.cmdQueue, a_rdir, CL_TRUE, CL_MAP_READ, 0, a_size*sizeof(float4), 0, 0, 0, &ciErr1); Lite_Hit* hits = (Lite_Hit*)clEnqueueMapBuffer(m_globals.cmdQueue, a_hits, CL_TRUE, CL_MAP_WRITE, 0, a_size*sizeof(Lite_Hit), 0, 0, 0, &ciErr1); uint* flgs = (uint*) clEnqueueMapBuffer(m_globals.cmdQueue, m_rays.rayFlags, CL_TRUE, CL_MAP_READ, 0, a_size*sizeof(uint), 0, 0, 0, &ciErr1); const float4* nodes = (const float4*)&m_scnBVH.nodes[0]; const float4* plist = (const float4*)&m_scnBVH.primListData[0]; IntegratorCommon* pCore = dynamic_cast<IntegratorCommon*>(m_pIntegrator); if (pCore == nullptr) { std::cerr << "GPUOCLLayer::runTraceCPU: bad dynamic cast for integrator" << std::endl; return; } #pragma omp parallel for for (int i = 0; i < a_size; i++) { uint flags = flgs[i]; if (!rayIsActiveU(flags)) continue; float3 rayPos = to_float3(rpos[i]); float3 rayDir = to_float3(rdir[i]); hits[i] = pCore->rayTrace(rayPos, rayDir, flags); } CHECK_CL(clEnqueueUnmapMemObject(m_globals.cmdQueue, a_rpos, rpos, 0, 0, 0)); CHECK_CL(clEnqueueUnmapMemObject(m_globals.cmdQueue, a_rdir, rdir, 0, 0, 0)); CHECK_CL(clEnqueueUnmapMemObject(m_globals.cmdQueue, a_hits, hits, 0, 0, 0)); CHECK_CL(clEnqueueUnmapMemObject(m_globals.cmdQueue, m_rays.rayFlags, flgs, 0, 0, 0)); //CHECK_CL(clFinish(m_globals.cmdQueue)); } void GPUOCLLayer::runTraceShadowCPU(size_t a_size) { } void GPUOCLLayer::saveBlocksInfoToFile(cl_mem a_blocks, size_t a_size) { static int fileId = 0; std::vector<ZBlock> blocks(a_size); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, a_blocks, CL_TRUE, 0, blocks.size() * sizeof(ZBlock), &blocks[0], 0, NULL, NULL)); } void GPUOCLLayer::debugSaveFrameBuffer(const char* a_fileName, cl_mem targetBuff) { std::vector<float4> screenColor(m_width*m_height); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, targetBuff, CL_TRUE, 0, screenColor.size()*sizeof(float4), &screenColor[0], 0, NULL, NULL)); std::vector<float4> screenColor2(m_width*m_height); for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) screenColor2[y*m_width + x] = screenColor[IndexZBlock2D(x, y, m_width, MortonTable256)]; } int wh[2] = { m_width, m_height }; std::ofstream fout(a_fileName, std::ios::binary); fout.write((const char*)wh, sizeof(int) * 2); fout.write((const char*)&screenColor2[0], sizeof(float) * 4 * screenColor2.size()); fout.close(); } void GPUOCLLayer::debugSaveRays(const char* a_folderName, cl_mem rpos, cl_mem rdir) { std::vector<float4> rposCPU(m_rays.MEGABLOCKSIZE); std::vector<float4> rdirCPU(m_rays.MEGABLOCKSIZE); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, rpos, CL_TRUE, 0, rposCPU.size()*sizeof(float4), &rposCPU[0], 0, NULL, NULL)); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, rdir, CL_TRUE, 0, rdirCPU.size()*sizeof(float4), &rdirCPU[0], 0, NULL, NULL)); int isize = int(m_rays.MEGABLOCKSIZE); std::string fileName1 = std::string(a_folderName) + "rpos.array4f"; std::string fileName2 = std::string(a_folderName) + "rdir.array4f"; std::ofstream fout(fileName1.c_str(), std::ios::binary); fout.write((const char*)&isize, sizeof(int)); fout.write((const char*)&rposCPU[0], sizeof(float) * 4 * rposCPU.size()); fout.close(); std::ofstream fout2(fileName2.c_str(), std::ios::binary); fout2.write((const char*)&isize, sizeof(int)); fout2.write((const char*)&rdirCPU[0], sizeof(float) * 4 * rdirCPU.size()); fout2.close(); } void GPUOCLLayer::debugSaveRaysText(const char* a_folderName, cl_mem rpos, cl_mem rdir) { std::vector<float4> rposCPU(m_rays.MEGABLOCKSIZE); std::vector<float4> rdirCPU(m_rays.MEGABLOCKSIZE); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, rpos, CL_TRUE, 0, rposCPU.size()*sizeof(float4), &rposCPU[0], 0, NULL, NULL)); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, rdir, CL_TRUE, 0, rdirCPU.size()*sizeof(float4), &rdirCPU[0], 0, NULL, NULL)); int isize = int(m_rays.MEGABLOCKSIZE); std::string fileName1 = std::string(a_folderName) + "rpos.txt"; std::string fileName2 = std::string(a_folderName) + "rdir.txt"; std::ofstream fout(fileName1.c_str()); for (int i = 0; i < rposCPU.size(); i++) fout << rposCPU[i].x << " " << rposCPU[i].y << " " << rposCPU[i].z << " " << rposCPU[i].w << std::endl; fout.close(); std::ofstream fout2(fileName2.c_str()); for (int i = 0; i < rdirCPU.size(); i++) fout << rdirCPU[i].x << " " << rdirCPU[i].y << " " << rdirCPU[i].z << " " << rdirCPU[i].w << std::endl; fout2.close(); } void GPUOCLLayer::debugSaveFloat4Text(const char* a_fileName, cl_mem data) { std::vector<float4> rposCPU(m_rays.MEGABLOCKSIZE); CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, data, CL_TRUE, 0, rposCPU.size()*sizeof(float4), &rposCPU[0], 0, NULL, NULL)); int isize = int(m_rays.MEGABLOCKSIZE); std::ofstream fout(a_fileName); for (int i = 0; i < rposCPU.size(); i++) fout << rposCPU[i].x << " " << rposCPU[i].y << " " << rposCPU[i].z << " " << rposCPU[i].w << std::endl; fout.close(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GPUOCLLayer::Denoise(cl_mem textureIn, cl_mem textureOut, int w, int h, float smoothLvl) { const int w2 = blocks(w, 16) * 16; const int h2 = blocks(h, 16) * 16; size_t global_item_size[2] = { size_t(w2), size_t(h2) }; size_t local_item_size[2] = { 16, 16 }; int radius = int(smoothLvl) + 2; float noiseLvl = clamp(0.1f*smoothLvl, 0.0f, 1.0f); if (radius < 3) radius = 3; if (radius > 9) radius = 9; //cl_kernel myKernel = m_progs.imagep.kernel("BilateralFilter"); // NonLocalMeansFilter cl_kernel myKernel = m_progs.imagep.kernel("NonLocalMeansFilter"); // NonLocalMeansFilter CHECK_CL(clSetKernelArg(myKernel, 0, sizeof(cl_mem), (void*)&textureOut)); CHECK_CL(clSetKernelArg(myKernel, 1, sizeof(cl_mem), (void*)&textureIn)); CHECK_CL(clSetKernelArg(myKernel, 2, sizeof(cl_int), (void*)&w)); CHECK_CL(clSetKernelArg(myKernel, 3, sizeof(cl_int), (void*)&h)); CHECK_CL(clSetKernelArg(myKernel, 4, sizeof(cl_int), (void*)&radius)); CHECK_CL(clSetKernelArg(myKernel, 5, sizeof(cl_float), (void*)&noiseLvl)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, myKernel, 2, NULL, global_item_size, local_item_size, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } std::vector<uchar4> GPUOCLLayer::NormalMapFromDisplacement(int w, int h, const uchar4* a_data, float bumpAmt, bool invHeight, float smoothLvl) { //std::cout << "[cl_core]: CPU NormalMapFromDisplacement" << std::endl; //return Base::NormalMapFromDisplacement(w, h, a_data, bumpAmt, invHeight, smoothLvl); // std::cout << "[cl_core]: GPU NormalMapFromDisplacement" << std::endl; cl_int ciErr1 = CL_SUCCESS; cl_int ciErr2 = CL_SUCCESS; cl_image_format imgFormat; imgFormat.image_channel_order = CL_RGBA; imgFormat.image_channel_data_type = CL_UNORM_INT8; size_t maxSizeX = 0; size_t maxSizeY = 0; CHECK_CL(clGetDeviceInfo(m_globals.device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &maxSizeX, NULL)); CHECK_CL(clGetDeviceInfo(m_globals.device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &maxSizeY, NULL)); if (maxSizeX < w || maxSizeY < h) { std::cout << "[cl_core]: NormalMapFromDisplacement(); maxSizeX = " << maxSizeX << ", w = " << w << std::endl; std::cout << "[cl_core]: NormalMapFromDisplacement(); maxSizeY = " << maxSizeY << ", h = " << h << std::endl; std::cout << "[cl_core]: NormalMapFromDisplacement(); CPU fallback; Performance ALERT !!!" << std::endl; return Base::NormalMapFromDisplacement(w, h, a_data, bumpAmt, invHeight, smoothLvl); } const size_t maxWorkGroupSize = m_globals.m_maxWorkGroupSize; cl_mem textureIn = clCreateImage2D(m_globals.ctx, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, &imgFormat, size_t(w), size_t(h), size_t(w) * sizeof(uchar4), (void*)a_data, &ciErr1); cl_mem textureOut = clCreateImage2D(m_globals.ctx, CL_MEM_READ_WRITE, &imgFormat, size_t(w), size_t(h), 0, NULL, &ciErr2); if (ciErr1 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::NormalMapFromDisplacement, clCreateImage2D(1) failed"); if (ciErr2 != CL_SUCCESS) RUN_TIME_ERROR("GPUOCLLayer::NormalMapFromDisplacement, clCreateImage2D(2) failed"); if (smoothLvl >= 1.0f) // denoise input heightmap { Denoise(textureIn, textureOut, w, h, smoothLvl); std::swap(textureIn, textureOut); } // run kernel NormalmapFromHeight { const int w2 = blocks(w, 16) * 16; const int h2 = blocks(h, 16) * 16; size_t global_item_size[2] = { size_t(w2), size_t(h2) }; size_t local_item_size[2] = { 16, 16 }; int invH = invHeight ? 1 : 0; cl_kernel myKernel = m_progs.imagep.kernel("NormalmapFromHeight"); CHECK_CL(clSetKernelArg(myKernel, 0, sizeof(cl_mem), (void*)&textureOut)); CHECK_CL(clSetKernelArg(myKernel, 1, sizeof(cl_mem), (void*)&textureIn)); CHECK_CL(clSetKernelArg(myKernel, 2, sizeof(cl_int), (void*)&w)); CHECK_CL(clSetKernelArg(myKernel, 3, sizeof(cl_int), (void*)&h)); CHECK_CL(clSetKernelArg(myKernel, 4, sizeof(cl_int), (void*)&invHeight)); CHECK_CL(clSetKernelArg(myKernel, 5, sizeof(cl_float), (void*)&bumpAmt)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, myKernel, 2, NULL, global_item_size, local_item_size, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } // if (smoothLvl >= 1) // denoise output normalmap // { // std::swap(textureIn, textureOut); // Denoise(textureIn, textureOut, w, h, smoothLvl); // } const size_t origin[3] = { 0, 0, 0 }; const size_t region[3] = { size_t(w), size_t(h), 1 }; std::vector<uchar4> resData(w*h); CHECK_CL(clEnqueueReadImage(m_globals.cmdQueue, textureOut, CL_TRUE, origin, region, 0, 0, (void*)&resData[0], 0, NULL, NULL)); clReleaseMemObject(textureIn); textureIn = 0; clReleaseMemObject(textureOut); textureOut = 0; return resData; }
#include "speedometer.h" speedometer::speedometer(int num) { speed = 0; number = num; kill = false; } void speedometer::increment() { if (speed < 200) speed++; } void speedometer::decrement() { if (speed > 0) speed--; } void speedometer::Kill() { kill = true; } int speedometer::main(void) { while (!kill) { std::cout << "Speedometer Car : " << number << " " << speed << "km/h" << std::endl; Sleep(2000); } return 0; }
/*********************************************************************** created: Sun Jan 11 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUITextureTarget_h_ #define _CEGUITextureTarget_h_ #include "CEGUI/RenderTarget.h" namespace CEGUI { /*! \brief Specialisation of RenderTarget interface that should be used as the base class for render-to-texture targets (RTT) - RenderTargets using textures. */ class CEGUIEXPORT TextureTarget : virtual public RenderTarget { public: TextureTarget(bool addStencilBuffer) : d_usesStencil(addStencilBuffer) {} virtual ~TextureTarget(); /*! \brief Clear the surface of the underlying texture. */ virtual void clear() = 0; /*! \brief Return a pointer to the CEGUI::Texture that the TextureTarget is using. \return Texture object that the TextureTarget uses when rendering imagery. */ virtual Texture& getTexture() const = 0; /*! \brief Used to declare to the TextureTarget the largest size, in pixels, of the next set of incoming rendering operations. \note The main purpose of this is to allow for the implementation to resize the underlying texture so that it can hold the imagery that will be drawn. \param sz Size object describing the largest area that will be rendered in the next batch of rendering operations. \exception InvalidRequestException May be thrown if the TextureTarget would not be able to handle the operations rendering content of the given size. */ virtual void declareRenderSize(const Sizef& sz) = 0; /*! \brief Return whether this TextureTarget has a stencil buffer attached or not. \return - true if a stencil buffer is attached - false if no stencil buffer is attached */ bool getUsesStencil() const; protected: //! Determines if the instance has a stencil buffer attached or not bool d_usesStencil; }; } // End of CEGUI namespace section #endif // end of guard _CEGUITextureTarget_h_
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwon <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/17 19:05:54 by jwon #+# #+# */ /* Updated: 2020/11/29 12:27:00 by jwon ### ########.fr */ /* */ /* ************************************************************************** */ #include "ZombieEvent.hpp" std::string zombieTypePicker(int idx) { std::string type; std::string types[10] = { "walker", "runner", "ghoul", "crawler", "screamer", "bonie", "puker", "stalker", "splitter", "exploder"}; srand(time(NULL)); if (idx == 42) type = types[rand() % 10]; else type = types[idx - 1]; std::cout << "\n## Zombie type is <" << type << "> ##" << std::endl; std::cout << std::endl; return (type); } int zombieTypeInput(void) { int input; bool loop; std::cout << "\n┌────────────────────── Type of zombies ─────────────────────────┐" << std::endl; std::cout << "│ 1. walker 2. runner 3. ghoul 4. crawler 5. screamer │" << std::endl; std::cout << "│ 6. bonie 7. puker 8. stalker 9. splitter 10. exploder │" << std::endl; std::cout << "│ * If you enter \'42\', the type is randomly defined. │" << std::endl; std::cout << "└────────────────────────────────────────────────────────────────┘" << std::endl; loop = true; while (loop) { std::cout << ">> Please choose the type of zombie : "; std::cin >> input; if (std::cin.fail()) { std::cout << "* Error: Invalid value." << std::endl; std::cin.clear(); std::cin.ignore(256, '\n'); continue ; } if (std::cin.eof()) return (0); if (input == 42 || (input >= 1 && input <= 10)) loop = false; else std::cout << "* Error: Input value is out of range." << std::endl; } return (input); } std::string zombieNameInput(void) { std::string input; std::cout << ">> Please name the zombie : "; std::cin >> input; if (std::cin.fail()) { std::cout << "* Error: Invalid value." << std::endl; std::cin.clear(); std::cin.ignore(256, '\n'); return (zombieNameInput()) ; } if (std::cin.eof()) return (""); return ((std::string)input); } void makeRandomZombie(ZombieEvent event) { int num; std::cout << ">> How many zombies do you need? : "; std::cin >> num; if (std::cin.fail()) { std::cout << "* Error: Invalid value." << std::endl; std::cin.clear(); std::cin.ignore(256, '\n'); return (makeRandomZombie(event)) ; } if (std::cin.eof()) return ; for (int i = 0 ; i < num ; i++) { usleep(1000000); event.randomChump(); } if (num > 0) std::cout << "\n## Zombies were born. ##" << std::endl; } int main(void) { int idx; std::string type; std::string name; Zombie *slave; ZombieEvent event; Zombie("master", "jwon"); std::cout << "\n## King of the zombie, jwon was born. ##" << std::endl; std::cout << "\n## Now, Let's make a slave zombies. ##" << std::endl; if (!(idx = zombieTypeInput())) return (-1); type = zombieTypePicker(idx); if ((name = zombieNameInput()) == "") return (-1); event.setZombieType(type); slave = event.newZombie(name); std::cout << "\n## Zombie " << name << " was born. ##" << std::endl; std::cout << std::endl; delete(slave); makeRandomZombie(event); return (0); }
class Solution { public: string removeDuplicates(string S) { // 本题用栈实现 stack<char> st; // 是char类型! for(char s : S){ // 类Python语法 if(st.empty() || s != st.top()){ // 待输入元素和栈顶元素比较,如果相同,直接让栈顶元素出栈。反之,让待入栈元素入栈。 st.push(s); }else{ st.pop(); } } string result; while(!st.empty()){ result += st.top(); // 类Python语法,char字符相加 st.pop(); } reverse(result.begin(),result.end()); // 反转,因为栈是FILO return result; } }; // reference https://mp.weixin.qq.com/s/eynAEbUbZoAWrk0ZlEugqg
#include "playertablemodel.h" #include <parser/outputparser.h> #include <utility> // std::move PlayerTableModel::PlayerTableModel(QObject* parent) : QAbstractTableModel(parent), headers({"Name", "Score", "Ping"}) { } QList<Player> PlayerTableModel::getPlayers() const { return players; } void PlayerTableModel::setPlayers(QList<Player> players) { emit layoutAboutToBeChanged(); this->players = std::move(players); emit layoutChanged(); } QList<QString> PlayerTableModel::getHeaders() const { return headers; } void PlayerTableModel::setHeaders(QList<QString> headers) { this->headers = std::move(headers); } int PlayerTableModel::rowCount(const QModelIndex&) const { return players.size(); } int PlayerTableModel::columnCount(const QModelIndex&) const { return headers.size(); } QVariant PlayerTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); else if (role == Qt::DisplayRole) { return getDataFromIndex(index); } else { return QVariant(); } } QVariant PlayerTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section < headers.size()) { return headers[section]; } else { return QVariant(); } } QVariant PlayerTableModel::getDataFromIndex(const QModelIndex& index) const { QVariant data; if (index.row() < players.size()) { if (index.column() == 0) { data = players[index.row()].getNameHtml(); } else if (index.column() == 1) { data = players[index.row()].getScore(); } else if (index.column() == 2) { data = players[index.row()].getPing(); } } return data; }
/****************************************************************************** * CommandFactory * * Authors: * Chantel Frizzell, Jeremy DeHaan * * Date Last Modified: * 2017-03-13 * * The command factory is used to aid in code reusibilty. Generates commands for * any type of command. ******************************************************************************/ #ifndef COMMANDFACTORY_H #define COMMANDFACTORY_H #include "command.h" #include <string> /* * The CommandFactory class generates commands. */ class CommandFactory { public: /* * Creates a Commands based on a given line read from a file. */ static Command* createCommand(std::string line); }; #endif //COMMANDFACTORY_H
#include "Approach.h" Approach::Approach(Boid* parent, sf::Vector2f* target, float weight) : SteeringBehaviour(parent) { this->target = target; this->weight = weight; type = SB_APPROACH; name = "Approach"; } sf::Vector2f Approach::CalculateSteeringForce() { return Seek(*target); }
/* * sais.h * * Created on: Sep 27, 2013 * Author: vbonnici */ /* * sais.h for sais-lite * Copyright (c) 2008-2010 Yuta Mori All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /* * adapted by vbonnici to deal with dna5_t sequences */ #ifndef SAIS_H_ #define SAIS_H_ //#define SAIS_DEBUG #include <assert.h> #include <stdlib.h> //#include "Sequence.h" #include "DNA5Alphabet.h" namespace dolierlib{ class sais_base_array{ public: virtual ~sais_base_array(){}; virtual _si64 get(_si64 i) = 0; virtual void set(_si64 i, _si64 val) = 0; virtual _si64 update(_si64 i, _si64 val) = 0; virtual _si64 decrease(_si64 i, _si64 val) = 0; }; class sais_int_array: public sais_base_array{ private: _si64 *m_a; _si64 m_pos; public: sais_int_array(_si64 *m_array, _si64 pos) : m_a(m_array), m_pos(pos) {}; virtual _si64 get(_si64 i) { #ifdef SAIS_DEBUG if(i<0)std::cout<<"int_array:get_negative "<<i<<"\n"; #endif return m_a[m_pos + i]; }; virtual void set(_si64 i, _si64 val) { #ifdef SAIS_DEBUG if(i<0)std::cout<<"int_array:set_negative_pos "<<i<<"\n"; if(val<0)std::cout<<"int_array:set_negative_value "<<val<<"\n"; #endif m_a[m_pos + i] = val; }; virtual _si64 update(_si64 i, _si64 val){ #ifdef SAIS_DEBUG if(i<0)std::cout<<"int_array:update_negative_pos "<<i<<"\n"; if(val<0)std::cout<<"int_array:update_negative_value "<<val<<" ("<<m_a[m_pos +i]<<")\n"; if(m_a[m_pos +i]+val<0)std::cout<<"int_array:update_negative_result "<<(m_a[m_pos +i]+val)<<" ("<<m_a[m_pos +i]<<")\n"; #endif return m_a[m_pos +i] += val; }; virtual _si64 decrease(_si64 i, _si64 val){ #ifdef SAIS_DEBUG if(i<0)std::cout<<"int_array:decrease_negative_pos "<<i<<"\n"; #endif //return m_a[m_pos +i] -= val; m_a[m_pos +i] -= val; return m_a[m_pos +i]; }; }; //class sais_sequence_array: public sais_base_array{ //private: // Sequence* m_seq; // usize_t m_pos; //public: // sais_sequence_array(Sequence* seq, usize_t pos) : m_seq(seq), m_pos(pos) {}; // virtual int get(int i) { //#ifdef SAIS_DEBUG // if(i<0)std::cout<<"seq_array:get_negative"; //#endif // return m_seq->getCode(m_pos + i); // }; // virtual void set(int i, int val) { //#ifdef SAIS_DEBUG // if(i<0)std::cout<<"seq_array:set_negative_pos"; // if(val<0)std::cout<<"seq_array:set_negative_value"; //#endif // m_seq->setCode(m_pos + i, val); // }; // virtual int update(int i, int val){return 0;}; //}; template<typename T> class sais_generic_array: public sais_base_array{ private: T *m_seq; _si64 m_pos; _si64 _length; public: sais_generic_array(T *seq, _si64 pos, _si64 length) : m_seq(seq), m_pos(pos), _length(length) {}; virtual _si64 get(_si64 i) { #ifdef SAIS_DEBUG if(i<0)std::cout<<"seq_array:get_negative"; if(i+m_pos >= _length)std::cout<<"seq_array:get_overflow "<<i<<" "<<m_pos<<" "<<_length; #endif //std::cout<<"seq_array:get "<<i<<" "<<m_pos<<" "<<_length; return m_seq[m_pos + i]; }; virtual void set(_si64 i, _si64 val) { #ifdef SAIS_DEBUG if(i<0)std::cout<<"seq_array:set_negative_pos"; if(val<0)std::cout<<"seq_array:set_negative_value"; #endif m_seq[m_pos + i] = val; }; virtual _si64 update(_si64 i, _si64 val){return 0;}; virtual _si64 decrease(_si64 i, _si64 val){return 0;}; }; void sais_get_counts(sais_base_array* T, sais_base_array* C, _si64 n, _si64 k) { for(_si64 i = 0; i < k; ++i) { C->set(i, 0); } for(_si64 i = 0; i < n; ++i) { C->update(T->get(i), 1); } } void sais_get_buckets(sais_base_array* C, sais_base_array* B, _si64 k, bool end) { _si64 i, sum = 0; if (end != false) { for(i = 0; i < k; ++i) { sum += C->get(i); B->set(i, sum); } } else { for(i = 0; i < k; ++i) { sum += C->get(i); B->set(i, sum - C->get(i)); } } } void sais_induce_SA(sais_base_array* T, _si64* SA, sais_base_array* C, sais_base_array* B, _si64 n, _si64 k){ _si64 b, i, j; _si64 c0, c1; /* compute SAl */ if(C == B) { sais_get_counts(T, C, n, k); } sais_get_buckets(C, B, k, false); /* find starts of buckets */ j = n - 1; b = B->get(c1 = T->get(j)); SA[b++] = ((0 < j) && (T->get(j - 1) < c1)) ? ~j : j; for(i = 0; i < n; ++i) { j = SA[i]; SA[i] = ~j; if(0 < j) { if((c0 = T->get(--j)) != c1) { B->set(c1, b); b = B->get(c1 = c0); } SA[b++] = ((0 < j) && (T->get(j - 1) < c1)) ? ~j : j; } } /* compute SAs */ if(C == B) { sais_get_counts(T, C, n, k); } sais_get_buckets(C, B, k, true); /* find ends of buckets */ for(i = n - 1, b = B->get(c1 = 0); 0 <= i; --i) { if(0 < (j = SA[i])) { if((c0 = T->get(--j)) != c1) { B->set(c1, b); b = B->get(c1 = c0); } SA[--b] = ((j == 0) || (T->get(j - 1) > c1)) ? ~j : j; } else { SA[i] = ~j; } } } /* find the suffix array SA of T[0..n-1] in {0..k-1}^n use a working space (excluding T and SA) of at most 2n+O(1) for a constant alphabet */ _si64 sais_sa_is(sais_base_array* T, _si64 *SA, _si64 fs, _si64 n, _si64 k){ #ifdef SAIS_DEBUG std::cout<<">sais_sa_is\n"; #endif sais_base_array *C=NULL, *B=NULL, *RA=NULL; _si64 i, j, c, m, p, q, plen, qlen, name, pidx = 0; _si64 c0, c1; bool diff; /* stage 1: reduce the problem by at least 1/2 sort all the S-substrings */ if(k <= fs) { C = new sais_int_array(SA, n); B = (k <= (fs - k)) ? new sais_int_array(SA, n + k) : C; } else { B = C = new sais_int_array(new _si64[k], 0); } #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:1.0\n"; #endif sais_get_counts(T, C, n, k); sais_get_buckets(C, B, k, true); /* find ends of buckets */ for(i = 0; i < n; ++i) { SA[i] = 0; } for(i = n - 2, c = 0, c1 = T->get(n - 1); 0 <= i; --i, c1 = c0) { if((c0 = T->get(i)) < (c1 + c)) { c = 1; } //else if(c != 0) { SA[B->update(c1, -1)] = i + 1; c = 0; } else if(c != 0) { SA[B->decrease(c1, 1)] = i + 1; c = 0; } } #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:1.0.1\n"; #endif sais_induce_SA(T, SA, C, B, n, k); #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:1.0.2\n"; #endif if(C != NULL){ if(B != C) delete B; delete C; } //if(B != NULL) delete B; C = NULL; B = NULL; #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:1.1\n"; #endif /* compact all the sorted substrings into the first m items of SA 2*m must be not larger than n (proveable) */ for(i = 0, m = 0; i < n; ++i) { p = SA[i]; if((0 < p) && (T->get(p - 1) > (c0 = T->get(p)))) { for(j = p + 1; (j < n) && (c0 == (c1 = T->get(j))); ++j) { } if((j < n) && (c0 < c1)) { SA[m++] = p; } } } j = m + (n >> 1); for(i = m; i < j; ++i) { SA[i] = 0; } /* init the name array buffer */ /* store the length of all substrings */ for(i = n - 2, j = n, c = 0, c1 = T->get(n - 1); 0 <= i; --i, c1 = c0) { if((c0 = T->get(i)) < (c1 + c)) { c = 1; } else if(c != 0) { SA[m + ((i + 1) >> 1)] = j - i - 1; j = i + 1; c = 0; } } /* find the lexicographic names of all substrings */ for(i = 0, name = 0, q = n, qlen = 0; i < m; ++i) { p = SA[i]; plen = SA[m + (p >> 1)]; diff = true; if(plen == qlen) { for(j = 0; (j < plen) && (T->get(p + j) == T->get(q + j)); ++j) { } if(j == plen) { diff = false; } } if(diff != false) { ++name; q = p; qlen = plen; } SA[m + (p >> 1)] = name; } #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:2\n"; #endif /* stage 2: solve the reduced problem recurse if names are not yet unique */ if(name < m) { RA = new sais_int_array(SA, n + fs - m); for(i = m + (n >> 1) - 1, j = n + fs - 1; m <= i; --i) { if(SA[i] != 0) { SA[j--] = SA[i] - 1; } } sais_sa_is(RA, SA, fs + n - m * 2, m, name); if(RA != NULL) delete RA; RA = NULL; for(i = n - 2, j = m * 2 - 1, c = 0, c1 = T->get(n - 1); 0 <= i; --i, c1 = c0) { if((c0 = T->get(i)) < (c1 + c)) { c = 1; } else if(c != 0) { SA[j--] = i + 1; c = 0; } /* get p1 */ } for(i = 0; i < m; ++i) { SA[i] = SA[SA[i] + m]; } /* get index */ } #ifdef SAIS_DEBUG std::cout<<">sais_sa_is:3\n"; #endif /* stage 3: induce the result for the original problem */ if(k <= fs) { C = new sais_int_array(SA, n); B = (k <= (fs - k)) ? new sais_int_array(SA, n + k) : C; } else { B = C = new sais_int_array(new _si64[k], 0); } /* put all left-most S characters into their buckets */ sais_get_counts(T, C, n, k); sais_get_buckets(C, B, k, true); /* find ends of buckets */ for(i = m; i < n; ++i) { SA[i] = 0; } /* init SA[m..n-1] */ for(i = m - 1; 0 <= i; --i) { j = SA[i]; SA[i] = 0; //SA[B->update(T->get(j), -1)] = j; SA[B->decrease(T->get(j), 1)] = j; } sais_induce_SA(T, SA, C, B, n, k); if(C != NULL){ if(B != C) delete B; delete C; } C = NULL; B = NULL; #ifdef SAIS_DEBUG std::cout<<"<sais_sa_is\n"; #endif return pidx; } //usize_t* //sais_build_SA(Sequence& seq){ //#ifdef SAIS_DEBUG // std::cout<<">sais_build_SA\n"; //#endif // usize_t *SA = new usize_t[seq.length()]; // usize_t n = seq.length(); // usize_t k = seq.alphabet_size() +1; // // if((seq.length() < n) || // (k <= 0)) { //#ifdef SAIS_DEBUG // std::cout<<"<sais_build_SA\n"; //#endif // return SA; // } // if(n <= 1) { if(n == 1) { SA[0] = 0; } //#ifdef SAIS_DEBUG // std::cout<<"<sais_build_SA\n"; //#endif // return SA; // } // // //sa_is(sais_base_array* T, usize_t *SA, int fs, int n, int k){ // sais_sa_is(new sais_sequence_array(&seq, 0), SA, 0, n, k); //#ifdef SAIS_DEBUG // std::cout<<"<sais_build_SA\n"; //#endif // return SA; //} usize_t* sais_build_SA(dna5_t *seq, usize_t length){ #ifdef SAIS_DEBUG std::cout<<">sais_build_SA\n"; #endif _si64 *SA = new _si64[length]; _si64 n = length; _si64 k = DNA5Alphabet::size() + 1; /* if((length < n) || (k <= 0)) { #ifdef SAIS_DEBUG std::cout<<"<sais_build_SA\n"; #endif return SA; } if(n <= 1) { if(n == 1) { SA[0] = 0; } #ifdef SAIS_DEBUG std::cout<<"<sais_build_SA\n"; #endif return SA; } */ //sa_is(sais_base_array* T, usize_t *SA, int fs, int n, int k){ sais_generic_array<dna5_t> gseq(seq, 0, length); sais_sa_is(&gseq, SA, 0, n, k); #ifdef SAIS_DEBUG std::cout<<"<sais_build_SA\n"; #endif usize_t *SSA = new usize_t[length]; for(usize_t i=0; i<length; i++){ SSA[i]=SA[i]; if(SA[i]<=0){ std::cout<<"SA <= 0; "<<i<<" "<<SA[i]<<"\n"; } } delete [] SA; return SSA; } } #endif /* SAIS_H_ */
#pragma once #include <string> using namespace std; class Reference{ protected: string lastName; string firstName; int year; string title; string editionPlace; string editor; public: Reference(string _lastName, string _firstName,string _title, string _edPlace, string _editor,int _year){ firstName = _firstName; lastName = _lastName; year = _year; title = _title; editionPlace = _edPlace; editor = _editor; } virtual void print(){ cout<<lastName<<", "<<firstName<<" ("<<year<<")."; } };
#include "employee.h" Employee::Employee() { name=""; number=0; money=0.0; } int Employee::employeeMax=1000; Employee::~Employee() { cout << "bye!" << endl; }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); database = new Database; setWindowIcon(QIcon(":/icons/images/ic_launcher.png")); setWindowTitle("MCRC Ground Control Station"); //3D ui->visualization_3D->setVisible(false); //graph view DISPLAY_gyroscope = new Gyroscopeview(ui->graphicsView); connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(set_start())); DISPLAY_mg = new Magview(ui->magView); connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(set_start())); setpoint = new Setpoint(ui->widget_map); ui->view_GPSlabel->setText("0.23"); ui->view_GPStext->setText("GPS:"); //signal plot signal_choose = new Signalchoose; //signal_choose->start(); signal_choose->hide(); signal_choose->wave_thread->plot_thread->chart_plot = ui->waveplotchart; //connect(ui->clearbutton,SIGNAL(clicked()),signal_choose->plot_thread,SLOT(clear_data())); QFileInfo file("./resource/map/offlinemap_demo/demo/1_11.html");//1_11 :/html/map/offlinemap_demo/demo/1_11.html /home/chnn/MCRC/offlinemap_demo/demo/520.html QString url = "file:///"; url += file.absoluteFilePath(); ui->widget_map->setUrl(QUrl(url)); //ui->widget_map->hide(); // ui->widget_la_long->hide(); // ui->widget_map_data->hide(); // ui->widget_map_rightcommand->hide(); connect(signal_choose->wave_thread->plot_thread->serial_setting->serial_thread, SIGNAL(data_progressfinished()), this, SLOT(display_dashboard()));//serial receive finished--display dash board connect(database->databasethread,SIGNAL(data2GCSfinished()), this, SLOT(display_dashboard()));//serial receive finished--display dash board connect(database->databasethread,SIGNAL(data2GCSfinished()), signal_choose->wave_thread, SLOT(emit_addpoints())); m_jsContext = new Document(ui->stackedWidget_rightmap); m_webChannel = new QWebChannel(ui->stackedWidget_rightmap); m_webChannel->registerObject("context", m_jsContext); ui->widget_map->page()->setWebChannel(m_webChannel); connect(m_jsContext, &Document::recvdMsg, this, [this](const QString &msg1,const QString &msg2) { ui->label_Latitude->setText(QString("%1").arg(msg1)); ui->label_longitude->setText(QString("%1").arg(msg2)); //qDebug()<<fixed<<qSetRealNumberPrecision(7)<<msg2.toDouble(); m_jsContext->savepoints(msg2.toDouble(),msg1.toDouble()); }); connect(m_jsContext, &Document::recvdMsg_newpoint, this, [this](const QString &msg1,const QString &msg2,quint8 index_point) { ui->label_Latitude->setText(QString("%1").arg(msg1)); ui->label_longitude->setText(QString("%1").arg(msg2)); m_jsContext->changepoints(msg2.toDouble(),msg1.toDouble(),index_point); }); //map----set point & clear & move flag connect(ui->btnSend, &QPushButton::clicked, this, [this]() { m_jsContext->sendMsg(ui->widget_map->page(), "clear"); m_jsContext->uiclear_init();map_Progress_Bar.MAP_POINTS = 0;}); connect(ui->toolButton_setpoint, &QToolButton::clicked, this, [this]() { m_jsContext->sendMsg(ui->widget_map->page(), "setpoint");}); connect(ui->toolButton_moveflag, &QToolButton::clicked, this, [this]() { m_jsContext->sendMsg(ui->widget_map->page(), "moveflag"); }); connect(signal_choose->wave_thread->plot_thread->serial_setting->serial_thread, SIGNAL(data_progressfinished()), this, SLOT(labei_display())); connect(database->databasethread,SIGNAL(data2GCSfinished()), this, SLOT(labei_display())); connect(signal_choose->wave_thread->plot_thread->serial_setting->serial_thread, SIGNAL(data_progressfinished()), this, SLOT(display_3D())); connect(database->databasethread,SIGNAL(data2GCSfinished()), this, SLOT(display_3D())); ui->pushButton->setStyleSheet("QPushButton{background-color:black;color: white; border-radius: 10px; border: 2px groove gray;border-style: outset;}" "QPushButton:hover{background-color:white; color: black;}" "QPushButton:pressed{background-color:rgb(85, 170, 255);border-style: inset; }"); protocolsetting = new Setting(); protocolsetting->package_command->serial_protocol = signal_choose->wave_thread->plot_thread->serial_setting; connect(protocolsetting->package_command,&Package::map_progressbar,this,[this]() { if(map_Progress_Bar.MAP_POINTS < 100) ui->progressBar_mappoints->setValue(map_Progress_Bar.MAP_POINTS); else{ ui->progressBar_mappoints->setValue(100); ui->progressBar_mappoints->setValue(0); } }); //signal_choose->wave_thread->sensordatabase = database; ui->toolButton_setpoint->setCheckable(true); } MainWindow::~MainWindow() { delete ui; } void MainWindow::display_3D() { ui->visualization_3D->update_angles(AP_DATA2GCS);//3D view } void MainWindow::labei_display() { ui->label_acc_x->setText(QString::number(AP_DATA2GCS.UAV_INS_Attitude[2])); ui->label_acc_y->setText(QString::number(AP_DATA2GCS.UAV_INS_Attitude[1])); ui->label_acc_z->setText(QString::number(AP_DATA2GCS.UAV_INS_Attitude[0])); } void MainWindow::display_dashboard() { DISPLAY_gyroscope->setRoll(AP_DATA2GCS.UAV_INS_Attitude[2]); ui->label_roll->setText(QString::number(AP_DATA2GCS.UAV_INS_Attitude[2])); DISPLAY_gyroscope->setPitch(AP_DATA2GCS.UAV_INS_Attitude[1]); ui->label_pitch->setText(QString::number(AP_DATA2GCS.UAV_INS_Attitude[1])); DISPLAY_mg->setmagyaw(AP_DATA2GCS.UAV_INS_Attitude[0]); } void MainWindow::on_button_3D_clicked() { static bool c ; c = !c; ui->visualization_3D->setVisible(c); ui->visualization_3D->visualization_state(c); } //debug void MainWindow::set_start() { QString str_x = ui->start_x->text(); int start_x = str_x.toInt(); QString str_y = ui->start_y->text(); int start_y = str_y.toInt(); QString str_width = ui->width->text(); int width = str_width.toInt(); QString str_height = ui->height->text(); int height = str_height.toInt(); QString str_other = ui->other->text(); int other = str_other.toInt(); DISPLAY_gyroscope->paint_display(start_x,start_y,width,height,other); DISPLAY_mg->set_mag(start_x,start_y,width,height,other); } void MainWindow::on_toolButton_serial_clicked() { signal_choose->wave_thread->plot_thread->serial_setting->show(); } void MainWindow::on_verticalSlider_pitch_valueChanged(int value) { DISPLAY_gyroscope->setPitch(value); ui->label_pitch->setText(QString::number(value)); } void MainWindow::on_dial_pitch_valueChanged(int value) { DISPLAY_gyroscope->setRoll(value); ui->label_roll->setText(QString::number(value)); } void MainWindow::on_signal_choose_clicked() { signal_choose->show(); } void MainWindow::on_clearbutton_clicked() { signal_choose->wave_thread->plot_thread->clear_data(); } void MainWindow::on_toolButton_9_clicked() { ui->stackedWidget_rightmap->setCurrentIndex(1); } void MainWindow::on_toolButton_8_clicked() { ui->stackedWidget_rightmap->setCurrentIndex(0); } void MainWindow::on_toolButton_mappoints_clicked() { m_jsContext->mappoints->show_hide(); } void MainWindow::on_toolButton_setting_clicked() { protocolsetting->show_hide(); } void MainWindow::on_toolButton_13_clicked() { protocolsetting->AP_Command(0); } void MainWindow::on_toolButton_12_clicked() { database->dialogshowhide(); } void MainWindow::on_toolButton_14_clicked() { database->readdatafromdatabase(); } void MainWindow::on_toolButton_mappoints_send_clicked() { protocolsetting->package_command->AP_Trajectory_Planning();//发送地图航点轨迹规划到无人机 }
#ifndef STATEMACHINE_H #define STATEMACHINE_H #include <string> /** * A simple abstract class for a state machine. Users may apply commands to the * state machine, each prompting an internal state transition and the return of * an output in string form. * * Correct implementations are deterministic: applying the same commands in the * same order from the same initial state should always result in the same * end state. */ class StateMachine { public: virtual std::string apply(std::string command) = 0; }; #endif /* !STATEMACHINE_H */
/************************************************************* * > File Name : P2320.cpp * > Author : Tony * > Created Time : 2019/09/14 20:37:54 * > Algorithm : 二分 **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 200010; int a[maxn], m, h; int main() { m = read(); while (m) { a[++h] = (m + 1) / 2; m /= 2; } printf("%d\n", h); for (int i = h; i >= 1; --i) { printf("%d ", a[i]); } return 0; }
#include <vector> #include <stdlib.h> #include <iostream> #include <map> #include <unordered_map> #include <set> #include <queue> #include <stack> #include <algorithm> #include <stdio.h> #include <fstream> using namespace std; bool const cmp(const vector<int>& x1, const vector<int>& x2) // &一定要加 { return x1[0]>x2[2]; } class Solution { // 贪心思想 public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { if(intervals.size()<=1) return 0; //先按照起点排序 sort(intervals.begin(),intervals.end()); int res = 0; int end = intervals[0][1]; for(int i=1;i<intervals.size();i++) { if(intervals[i][0]<end) { res++; // 如果终点在之前 if(intervals[i][1]<end) end = intervals[i][1]; } else end = intervals[i][1]; } return res; } }; int main() { Solution2 s; vector<int> nums = {1,1,1,1,1}; int res = s.findTargetSumWays(nums,3); cout << res << endl; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/event.h" #if defined(USE_X11) #include <X11/Xlib.h> #endif #include <cstring> #include "ui/base/keycodes/keyboard_code_conversion.h" #include "ui/gfx/point3.h" #include "ui/gfx/interpolated_transform.h" #include "ui/gfx/transform.h" #if defined(USE_X11) #include "ui/base/keycodes/keyboard_code_conversion_x.h" #endif namespace { base::NativeEvent CopyNativeEvent(const base::NativeEvent& event) { #if defined(USE_X11) XEvent* copy = new XEvent; *copy = *event; return copy; #elif defined(OS_WIN) return event; #else NOTREACHED() << "Don't know how to copy base::NativeEvent for this platform"; return NULL; #endif } } // namespace namespace ui { Event::~Event() { #if defined(USE_X11) if (delete_native_event_) delete native_event_; #endif } bool Event::HasNativeEvent() const { base::NativeEvent null_event; std::memset(&null_event, 0, sizeof(null_event)); return !!std::memcmp(&native_event_, &null_event, sizeof(null_event)); } Event::Event(EventType type, int flags) : type_(type), time_stamp_(base::Time::NowFromSystemTime() - base::Time()), flags_(flags), delete_native_event_(false) { Init(); } Event::Event(const base::NativeEvent& native_event, EventType type, int flags) : type_(type), time_stamp_(EventTimeFromNative(native_event)), flags_(flags), delete_native_event_(false) { InitWithNativeEvent(native_event); } Event::Event(const Event& copy) : native_event_(copy.native_event_), type_(copy.type_), time_stamp_(copy.time_stamp_), flags_(copy.flags_), delete_native_event_(false) { } void Event::Init() { std::memset(&native_event_, 0, sizeof(native_event_)); } void Event::InitWithNativeEvent(const base::NativeEvent& native_event) { native_event_ = native_event; } LocatedEvent::~LocatedEvent() { } LocatedEvent::LocatedEvent(const base::NativeEvent& native_event) : Event(native_event, EventTypeFromNative(native_event), EventFlagsFromNative(native_event)), location_(EventLocationFromNative(native_event)), root_location_(location_) { } LocatedEvent::LocatedEvent(EventType type, const gfx::Point& location, const gfx::Point& root_location, int flags) : Event(type, flags), location_(location), root_location_(root_location) { } void LocatedEvent::UpdateForRootTransform(const Transform& root_transform) { // Transform has to be done at root level. DCHECK_EQ(root_location_.x(), location_.x()); DCHECK_EQ(root_location_.y(), location_.y()); gfx::Point3f p(location_); root_transform.TransformPointReverse(p); root_location_ = location_ = p.AsPoint(); } MouseEvent::MouseEvent(const base::NativeEvent& native_event) : LocatedEvent(native_event) { if (type() == ET_MOUSE_PRESSED) SetClickCount(GetRepeatCount(*this)); } MouseEvent::MouseEvent(EventType type, const gfx::Point& location, const gfx::Point& root_location, int flags) : LocatedEvent(type, location, root_location, flags) { } // static bool MouseEvent::IsRepeatedClickEvent( const MouseEvent& event1, const MouseEvent& event2) { // These values match the Windows defaults. static const int kDoubleClickTimeMS = 500; static const int kDoubleClickWidth = 4; static const int kDoubleClickHeight = 4; if (event1.type() != ET_MOUSE_PRESSED || event2.type() != ET_MOUSE_PRESSED) return false; // Compare flags, but ignore EF_IS_DOUBLE_CLICK to allow triple clicks. if ((event1.flags() & ~EF_IS_DOUBLE_CLICK) != (event2.flags() & ~EF_IS_DOUBLE_CLICK)) return false; base::TimeDelta time_difference = event2.time_stamp() - event1.time_stamp(); if (time_difference.InMilliseconds() > kDoubleClickTimeMS) return false; if (abs(event2.x() - event1.x()) > kDoubleClickWidth / 2) return false; if (abs(event2.y() - event1.y()) > kDoubleClickHeight / 2) return false; return true; } // static int MouseEvent::GetRepeatCount(const MouseEvent& event) { int click_count = 1; if (last_click_event_) { if (IsRepeatedClickEvent(*last_click_event_, event)) click_count = last_click_event_->GetClickCount() + 1; delete last_click_event_; } last_click_event_ = new MouseEvent(event.native_event()); if (click_count > 3) click_count = 3; last_click_event_->SetClickCount(click_count); return click_count; } // static MouseEvent* MouseEvent::last_click_event_ = NULL; int MouseEvent::GetClickCount() const { if (type() != ET_MOUSE_PRESSED) return 0; if (flags() & EF_IS_TRIPLE_CLICK) return 3; else if (flags() & EF_IS_DOUBLE_CLICK) return 2; else return 1; } void MouseEvent::SetClickCount(int click_count) { if (type() != ET_MOUSE_PRESSED) return; DCHECK(click_count > 0); DCHECK(click_count <= 3); int f = flags(); switch (click_count) { case 1: f &= ~EF_IS_DOUBLE_CLICK; f &= ~EF_IS_TRIPLE_CLICK; break; case 2: f |= EF_IS_DOUBLE_CLICK; f &= ~EF_IS_TRIPLE_CLICK; break; case 3: f &= ~EF_IS_DOUBLE_CLICK; f |= EF_IS_TRIPLE_CLICK; break; } set_flags(f); } TouchEventImpl::TouchEventImpl(const base::NativeEvent& native_event) : LocatedEvent(native_event), touch_id_(ui::GetTouchId(native_event)), radius_x_(GetTouchRadiusX(native_event)), radius_y_(GetTouchRadiusY(native_event)), rotation_angle_(GetTouchAngle(native_event)), force_(GetTouchForce(native_event)) { } TouchEventImpl::TouchEventImpl(EventType type, const gfx::Point& location, int touch_id, base::TimeDelta time_stamp) : LocatedEvent(type, location, location, 0), touch_id_(touch_id), radius_x_(0.0f), radius_y_(0.0f), rotation_angle_(0.0f), force_(0.0f) { set_time_stamp(time_stamp); } TouchEventImpl::~TouchEventImpl() { } void TouchEventImpl::UpdateForRootTransform(const Transform& root_transform) { LocatedEvent::UpdateForRootTransform(root_transform); gfx::Point3f scale; InterpolatedTransform::FactorTRS(root_transform, NULL, NULL, &scale); if (scale.x()) radius_x_ /= scale.x(); if (scale.y()) radius_y_ /= scale.y(); } EventType TouchEventImpl::GetEventType() const { return type(); } gfx::Point TouchEventImpl::GetLocation() const { return location(); } int TouchEventImpl::GetTouchId() const { return touch_id_; } int TouchEventImpl::GetEventFlags() const { return flags(); } base::TimeDelta TouchEventImpl::GetTimestamp() const { return time_stamp(); } float TouchEventImpl::RadiusX() const { return radius_x_; } float TouchEventImpl::RadiusY() const { return radius_y_; } float TouchEventImpl::RotationAngle() const { return rotation_angle_; } float TouchEventImpl::Force() const { return force_; } KeyEvent::KeyEvent(const base::NativeEvent& native_event, bool is_char) : Event(native_event, EventTypeFromNative(native_event), EventFlagsFromNative(native_event)), key_code_(KeyboardCodeFromNative(native_event)), is_char_(is_char), character_(0), unmodified_character_(0) { } KeyEvent::KeyEvent(EventType type, KeyboardCode key_code, int flags) : Event(type, flags), key_code_(key_code), is_char_(false), character_(GetCharacterFromKeyCode(key_code, flags)), unmodified_character_(0) { } uint16 KeyEvent::GetCharacter() const { if (character_) return character_; #if defined(OS_WIN) return (native_event().message == WM_CHAR) ? key_code_ : GetCharacterFromKeyCode(key_code_, flags()); #elif defined(USE_X11) if (!native_event()) return GetCharacterFromKeyCode(key_code_, flags()); DCHECK(native_event()->type == KeyPress || native_event()->type == KeyRelease); uint16 ch = 0; if (!IsControlDown()) ch = GetCharacterFromXEvent(native_event()); return ch ? ch : GetCharacterFromKeyCode(key_code_, flags()); #else NOTIMPLEMENTED(); return 0; #endif } uint16 KeyEvent::GetUnmodifiedCharacter() const { if (unmodified_character_) return unmodified_character_; #if defined(OS_WIN) // Looks like there is no way to get unmodified character on Windows. return (native_event().message == WM_CHAR) ? key_code_ : GetCharacterFromKeyCode(key_code_, flags() & EF_SHIFT_DOWN); #elif defined(USE_X11) if (!native_event()) return GetCharacterFromKeyCode(key_code_, flags() & EF_SHIFT_DOWN); DCHECK(native_event()->type == KeyPress || native_event()->type == KeyRelease); static const unsigned int kIgnoredModifiers = ControlMask | LockMask | Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask; XKeyEvent copy = native_event()->xkey; // bit-wise copy is safe. // We can't use things like (native_event()->xkey.state & ShiftMask), as it // may mask out bits used by X11 internally. copy.state &= ~kIgnoredModifiers; uint16 ch = GetCharacterFromXEvent(reinterpret_cast<XEvent*>(&copy)); return ch ? ch : GetCharacterFromKeyCode(key_code_, flags() & EF_SHIFT_DOWN); #else NOTIMPLEMENTED(); return 0; #endif } KeyEvent* KeyEvent::Copy() { KeyEvent* copy = new KeyEvent(::CopyNativeEvent(native_event()), is_char()); #if defined(USE_X11) copy->set_delete_native_event(true); #endif return copy; } TranslatedKeyEvent::TranslatedKeyEvent(const base::NativeEvent& native_event, bool is_char) : KeyEvent(native_event, is_char) { set_type(type() == ET_KEY_PRESSED ? ET_TRANSLATED_KEY_PRESS : ET_TRANSLATED_KEY_RELEASE); } TranslatedKeyEvent::TranslatedKeyEvent(bool is_press, KeyboardCode key_code, int flags) : KeyEvent((is_press ? ET_TRANSLATED_KEY_PRESS : ET_TRANSLATED_KEY_RELEASE), key_code, flags) { } void TranslatedKeyEvent::ConvertToKeyEvent() { set_type(type() == ET_TRANSLATED_KEY_PRESS ? ET_KEY_PRESSED : ET_KEY_RELEASED); } ScrollEvent::ScrollEvent(const base::NativeEvent& native_event) : MouseEvent(native_event) { if (type() == ET_SCROLL) { GetScrollOffsets(native_event, &x_offset_, &y_offset_); double start, end; GetGestureTimes(native_event, &start, &end); } else if (type() == ET_SCROLL_FLING_START) { bool is_cancel; GetFlingData(native_event, &x_offset_, &y_offset_, &is_cancel); } } GestureEventImpl::GestureEventImpl(EventType type, int x, int y, int flags, base::Time time_stamp, const GestureEventDetails& details, unsigned int touch_ids_bitfield) : LocatedEvent(type, gfx::Point(x, y), gfx::Point(x, y), flags), details_(details), touch_ids_bitfield_(touch_ids_bitfield) { set_time_stamp(base::TimeDelta::FromSeconds(time_stamp.ToDoubleT())); } GestureEventImpl::~GestureEventImpl() { } int GestureEventImpl::GetLowestTouchId() const { if (touch_ids_bitfield_ == 0) return -1; int i = -1; // Find the index of the least significant 1 bit while (!(1 << ++i & touch_ids_bitfield_)); return i; } } // namespace ui
// Singleton Design Pattern #include<bits/stdc++.h> using namespace std; // Admin class is a singleton class as in our system only one Admin can exist class Admin { public: string name; int id; static Admin *AdminInstance; private: // make the constructor private Admin(string name, int id) { this -> name = name; this -> id = id; } public: // static function to get the only instance static Admin* getInstance(string name, int id) { if(!AdminInstance) AdminInstance = new Admin(name, id); return AdminInstance; } }; // initializing static variable AdminInstance to nullptr Admin* Admin:: AdminInstance = nullptr; int main() { Admin *obj1 = Admin::getInstance("Venkat", 502); cout<<obj1->name<<endl; // we will get the reference of obj1 itself Admin *obj2 = Admin:: getInstance("Pavan", 502); cout<<obj2->name<<endl; return 0; }
#ifndef DYN_UI_NAVIGATOR_H #define DYN_UI_NAVIGATOR_H /******************************************************************************** ** Form generated from reading UI file 'navigator.ui' ** ** Created: Fri Nov 26 22:18:28 2010 ** by: Qt User Interface Compiler version 4.7.1 ********************************************************************************/ #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QComboBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QTabWidget> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> #include <QtGui/QMainWindow> #include <QDebug> QT_BEGIN_NAMESPACE class Ui_Navigator : public QWidget { public: QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout,*tabHLayout; QToolButton *backButton; QComboBox *addressBar; QToolButton *goButton; QTabWidget *tabWidget; QWidget *drives; QWidget *fav; QWidget *Navigator; QMainWindow *mw; public: Ui_Navigator(QWidget *Navigator,QMainWindow *mw) { this->Navigator = Navigator; this->mw = mw; if (Navigator->objectName().isEmpty()) Navigator->setObjectName(QString::fromUtf8("Navigator")); Navigator->resize(467, 97); verticalLayout = new QVBoxLayout(Navigator); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(2, 2, 2, 5); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(1); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); backButton = new QToolButton(Navigator); backButton->setObjectName(QString::fromUtf8("backButton")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(1); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(backButton->sizePolicy().hasHeightForWidth()); backButton->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); horizontalLayout->addWidget(backButton); addressBar = new QComboBox(Navigator); addressBar->setObjectName(QString::fromUtf8("addressBar")); //this->addressBar->setEditable(1); sizePolicy.setHeightForWidth(addressBar->sizePolicy().hasHeightForWidth()); addressBar->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); addressBar->setInsertPolicy(QComboBox::InsertAtTop); horizontalLayout->addWidget(addressBar); goButton = new QToolButton(Navigator); goButton->setObjectName(QString::fromUtf8("goButton")); sizePolicy.setHeightForWidth(goButton->sizePolicy().hasHeightForWidth()); goButton->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); horizontalLayout->addWidget(goButton); horizontalLayout->setStretch(1, 1); verticalLayout->addLayout(horizontalLayout); tabWidget = new QTabWidget(Navigator); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tabWidget->setTabPosition(QTabWidget::South); tabWidget->setTabsClosable(true); drives = new QWidget(); drives->setObjectName(QString::fromUtf8("drives")); tabHLayout = new QHBoxLayout(drives); tabWidget->addTab(drives, QString()); fav = new QWidget(); fav->setObjectName(QString::fromUtf8("fav")); tabWidget->addTab(fav, QString()); verticalLayout->addWidget(tabWidget); retranslateUi(Navigator); tabWidget->setCurrentIndex(0); QMetaObject::connectSlotsByName(Navigator); } // setupUi void retranslateUi(QWidget *Navigator) { Navigator->setWindowTitle(QApplication::translate("Navigator", "Form", 0, QApplication::UnicodeUTF8)); backButton->setText(QApplication::translate("Navigator", "Back", 0, QApplication::UnicodeUTF8)); goButton->setText(QApplication::translate("Navigator", "Go", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(drives), QApplication::translate("Navigator", "Meghajt\303\263", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(fav), QApplication::translate("Navigator", "Kedvencek", 0, QApplication::UnicodeUTF8)); } // retranslateUi void add_drive_button(QString button, QIcon icon){ QStringList letter = button.split("://"); QToolButton *drive = new QToolButton(drives); tabHLayout->addWidget(drive); QSizePolicy sizePolicy = QSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(1); sizePolicy.setVerticalStretch(0); drive->setObjectName(button); drive->setText(letter[1]); drive->setIcon(icon); drive->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); drive->setSizePolicy(sizePolicy); // signalokat itt kene letrehozni a buttonhoz connect(drive,SIGNAL(clicked()),mw,SLOT(driveButtonClicked())); } //adddrivebutton void addAddressBarItem(QString url){ this->addressBar->insertItem(0,url,url); this->addressBar->setCurrentIndex(0); } void setPreviousAddress(){ this->addressBar->setCurrentIndex(this->addressBar->currentIndex()+1); } }; namespace Ui { class Navigator: public Ui_Navigator {}; } // namespace Ui QT_END_NAMESPACE #endif // DYN_UI_NAVIGATOR_H
// // MenuLayer.hpp // CatchGirl // // Created by xin on 16/4/6. // // #ifndef MenuLayer_hpp #define MenuLayer_hpp #include <stdio.h> #include "cocos2d.h" #include "SceneManager.hpp" #include "ui/cocosGUI.h" #include "cocostudio/CocoStudio.h" using namespace ui; USING_NS_CC; class MenuLayer:public Layer{ public: CREATE_FUNC(MenuLayer); virtual bool init(); SceneManager * tsm; void touchCallback(Ref * pSender,Widget::TouchEventType type); }; #endif /* MenuLayer_hpp */
#include <cstdio> #include <iostream> #include <map> #include <vector> #include <queue> #include <cstring> #include <cmath> #include <algorithm> using namespace std; map<int,int>rupa; vector<int>saikat; int res; void bfs(int a,int b,map<int,vector<int> >sagar) { queue<int>q; int ans=0; res=0; q.push(a); rupa[a]=0; while(q.empty()==false) { int top=q.front(); for(int i=0;i<sagar[top].size();i++) { int taken=sagar[top][i]; if(rupa[taken]==0 && taken!=a) { rupa[taken]=rupa[top]+1; res=rupa[taken]; if(taken==b){ ans=1; break; } q.push(taken); } } if(ans==1) break; q.pop(); } } void gap(int x) { if(x<10) cout<<" "; } int main() { int x,y,z,i,j,w,ck,t=1; while(cin>>x) { int a[1000],b[1000]; map<int,vector<int> >sagar; for(i=1;i<=x;i++) { cin>>y; sagar[1].push_back(y); sagar[y].push_back(1); } for(i=2;i<=19;i++) { cin>>z; for(j=1;j<=z;j++) { cin>>w; sagar[i].push_back(w); sagar[w].push_back(i); } } cin>>ck; for(i=0;i<ck;i++) { cin>>a[i]>>b[i]; bfs(a[i],b[i],sagar); saikat.push_back(res); rupa.clear(); } cout<<"Test Set #"<<t<<endl; for(i=0;i<saikat.size();i++) { gap(a[i]); cout<<a[i]<<" "<<"to"<<" "; gap(b[i]); cout<<b[i]<<":"; gap(saikat[i]); cout<<saikat[i]<<endl; } t++; cout<<endl; sagar.clear(); saikat.clear(); } return 0; }
#include "create_cities.h" istream &operator >> (istream &in, create_cities &ob) { char *name_city = new char[101]; double h, m, s; cout << "Introduceti numele orasului: "; in.getline(name_city + 1, 101); int lg = strlen(name_city + 1); for (int i = 1; i <= lg; ++i) ob.pushC(name_city[i]); cout << "Introduceti orele, minutele si secundele pentru latitudine: "; in >> h >> m >> s; ob.lati = h + m * (1.0 / 60.0) + s * (1.0 / 3600.0); cout << "Introduceti orele, minutele si secundele pentru longitudine: "; in >> h >> m >> s; ob.longi = h + m * (1.0 / 60.0) + s * (1.0 / 3600.0); in.getline(name_city + 1, 101); delete[] name_city; return in; } ostream &operator << (ostream &out, create_cities ob) { for (int i = 1; i <= ob.name.size(); ++i) out << ob.name[i]; out << ' ' << ob.x << ' ' << ob.y << '\n'; return out; } void create_cities::setX() { x = R * cos(lati * PI / 180.0) * cos(longi * PI / 180.0); } void create_cities::setY() { y = R * cos(lati * PI / 180.0) * sin(longi * PI / 180.0); } void create_cities::pushC(char c) { name.push_back(c); } int create_cities::getX() { return x; } int create_cities::getY() { return y; } char create_cities::getC(int pos) { return name[pos]; } int create_cities::nameSize() { return name.size(); }
#pragma once #include "app.h" class team_items { public: team_items(u8* memory_pointer); ~team_items(); private: };
#ifndef __LayerEnemy_H__ #define __LayerEnemy_H__ #include "cocos2d.h" #include "Enemy.h" USING_NS_CC; //! 各种飞机的生命值 const int SMALL_MAXLIFE = 1; const int MID_MAXLIFE = 3; const int BIG_MAXLIFE = 5; class LayerEnemy :public CCLayer { public: CREATE_FUNC(LayerEnemy); bool init(); //! 小飞机 void addSmallEnemy(float dt); void smallEnemyMoveFinishedFCallBack(CCNode *node); void smallEnemyBlowUp(Enemy * smallEnemy); void removeSmallEnemyFCallBack(CCNode * target, void * data); //! 给removeAllEnemy调用 void removeAllSmallEnemy(); void removeAllEnemy(); //! smallEnemy的存储数组 CCArray * m_psmallArray; }; #endif
#include <bits/stdc++.h> using namespace std; #define int long long #define endl "\n" int32_t main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin>>n; int a[n]; for (int i=0; i<n; i++) { cin>>a[i]; } int max = a[0]; int sum = a[0]; for (int i=1; i<n; i++) { if(sum + a[i] <=0) { sum =0; } else if(sum + a[i] > max) { sum += a[i]; max = sum; } else { sum += a[i]; } } cout<<max<<endl; return 0; }
#include "Ball.h" Ball::Ball() { } // // license:GPLv3+ // Ported at: VisualPinball.Unity/VisualPinball.Unity/VPT/Ball/BallCollider.cs // void Ball::Collide3DWall(const Vertex3Ds& hitNormal, float elasticity, const float elastFalloff, const float friction, float scatter_angle) { }
#include <bits/stdc++.h> using namespace std; int main() { string a; cin>>a; int ans = 1; for(int i=0; i<a.length(); i++) { if(a[i]>='A' && a[i]<='Z') ans++; } cout<<ans<<endl; }
#ifndef TSDPDFMATCHER_H_ #define TSDPDFMATCHER_H_ #include "IPreMatcher.h" #include <string> #include <tinyxml2.h> class TsdPdfMatcher : public IPrematcher { public: TsdPdfMatcher(); virtual ~TsdPdfMatcher(); virtual bool init(const std::string& configXml) override; virtual bool doRegistration(obvious::SensorPolar2D* sensor, obvious::Matrix* M, obvious::Matrix* Mvalid, obvious::Matrix* N, obvious::Matrix* Nvalid, obvious::Matrix* S, obvious::Matrix* Svalid, obvious::Matrix& T) override; private: std::string _configXml; int _trials; int _sizeControlSet; double _epsThresh; double _zrand; }; #endif
#ifndef _BASE_THREAD_H_ #define _BASE_THREAD_H_ #include <string> #include <pthread.h> namespace base { class ThreadWorker { public: virtual ~ThreadWorker() {}; virtual void *run() = 0; }; class Thread { public: Thread(ThreadWorker *worker, std::string name = ""); ~Thread(); void start(); void join(); void set_priority(int priority); static pthread_t id(); static std::string id_str(); static const char *name(); static bool is_runing_in(pthread_t tid); private: static void *thread_main_func(void *data); private: static int count; private: pthread_t m_tid; ThreadWorker *m_worker; std::string m_name; bool m_is_started; bool m_is_joined; int m_priority; }; } #endif
#include "Builder.h" std::string Builder::getCpu() { return std::string("i7 7700K"); } std::shared_ptr<Memory> Builder::getMemory() { return std::make_shared<Memory>(16); } std::shared_ptr<Storage> Builder::getStorage() { return std::make_shared<Storage>(1024); }
// Copyright (c) 2014, OpenFlow // Author: kobemiller<kobemiller@126.com> // Created: 2014-07-03 // Description: // #ifndef OPENFLOW_AGENT_HANDLER_H #define OPENFLOW_AGENT_HANDLER_H #pragma once #include <vector> #include "rpc/agent/AgentService.h" namespace openflow { namespace agent { class CAgentHandler : public AgentServiceIf { public: CAgentHandler(); int32_t submit_task(const int32_t t_id); int32_t kill_task(); }; } } #endif
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Diseño y Análisis de Algoritmos * * Algoritmos constructivos y búsquedas por entornos * * @author Ángel Tornero Hernández * @date 12 Abr 2021 * @file GreedyAlgorithm.cc * */ #include "../include/GreedyAlgorithm.h" #include <iostream> const int BIG_NUMBER = 999999; std::vector<Machine*> GreedyAlgorithm::solve(PMSProblem& pmsp) { std::vector<Task*> shorterTasks = selectShorterTasks(pmsp); std::vector<Machine*> solution; for (int i = 0; i < pmsp.getm(); i++) { solution.push_back(new Machine({shorterTasks[i]})); } do { bestInsertion(pmsp, solution); } while (!allTasksAssigned(pmsp)); return solution; } void GreedyAlgorithm::assignNextTask(Machine* machine, Task* task) { machine->addTask(task); } std::vector<Task*> GreedyAlgorithm::selectShorterTasks(PMSProblem& pmsp) { Task* auxTask = new Task(-1, BIG_NUMBER, BIG_NUMBER); Task* shortestTask; std::vector<Task*> shorterTasks; for (int i = 0; i < pmsp.getm(); i++) { shortestTask = auxTask; for (int j = 0; j < pmsp.getn(); j++) { if (pmsp.getTask(j)->getProcessTime() + pmsp.getTask(j)->getSetupTimeZero() < shortestTask->getProcessTime() + shortestTask->getSetupTimeZero() && !pmsp.getTask(j)->assigned()) { shortestTask = pmsp.getTask(j); } } shortestTask->setAsAssigned(); shorterTasks.push_back(shortestTask); } delete auxTask; return shorterTasks; } bool GreedyAlgorithm::allTasksAssigned(PMSProblem& pmsp) { for (int i = 0; i < pmsp.getn(); i++) { if (!pmsp.getTask(i)->assigned()) { return false; } } return true; } void GreedyAlgorithm::bestInsertion(PMSProblem& pmsp, std::vector<Machine*>& solution) { int bestTCT = BIG_NUMBER; int bestTask; int bestPosition; int bestMachine; for (int i = 0; i < solution.size(); i++) { for (int j = 0; j < pmsp.getn(); j++) { if (pmsp.getTask(j)->assigned()) { continue; } int newPosition; int newTCT = calculateBestTCT(solution[i], pmsp.getTask(j), newPosition); if (newTCT < bestTCT) { bestTCT = newTCT; bestTask = j; bestPosition = newPosition; bestMachine = i; } } } solution[bestMachine]->insertTask(pmsp.getTask(bestTask), bestPosition); pmsp.getTask(bestTask)->setAsAssigned(); } int GreedyAlgorithm::calculateBestTCT(Machine* machine, Task* task, int& position) { int bestTCT = BIG_NUMBER; int actualTCT = TCT(machine->getTaskArray()); for (int i = 0; i < machine->assignedTasks() + 1; i++) { Machine aux(machine->getTaskArray()); aux.insertTask(task, i); int tct = TCT(aux.getTaskArray()); if (tct - actualTCT < bestTCT) { bestTCT = tct - actualTCT; position = i; } } return bestTCT; } int GreedyAlgorithm::TCT(std::vector<Task*> machine) { int sum = 0; for (int i = 0; i < machine.size(); i++) { sum += C(machine, i); } return sum; } int GreedyAlgorithm::C(std::vector<Task*> machine, int pos) { int sum = machine[0]->getSetupTimeZero() + machine[0]->getProcessTime(); for (int i = 0; i < pos; i++) { sum += machine[i]->getSetupTimeTo(machine[i + 1]->getId()) + machine[i + 1]->getProcessTime(); } return sum; } void GreedyAlgorithm::printSolution(std::vector<Machine*>& solution) { std::cout << "\n- Algoritmo Greedy:\n"; int complexTime = 0; for (int i = 0; i < solution.size(); i++) { std::cout << "\tMáquina " << i + 1 << " (" << TCT(solution[i]->getTaskArray()) << ") : { "; complexTime += TCT(solution[i]->getTaskArray()); for (int j = 0; j < solution[i]->assignedTasks(); j++) { std::cout << solution[i]->getTaskArray()[j]->getId() + 1 << ' '; } std::cout << "}\n"; } std::cout << "\tTiempo total: " << complexTime << '\n'; }
#include <iostream> using namespace std; //virtual function //Abstract class - MUST contain at least one pure virtual function , CANT create objects! Used as a template for creating other classes class Enemy { protected: int attackPwr{}; public: void setPwr(int x) { this -> attackPwr = x; } //virtual function - may be overrirden in deriver(inheritor) class virtual void attack(){cout<< "enemy attacks!"<<endl;} //Allows the Enemy pointer to access the method of the Ninja Object (inheritor) //internal logic of the pointer allows it to look for other implementations down the inheritance tree //Pure Virtual method - MUST be overloaded in derived(inheritor) class virtual void defense() = 0; }; class Ninja : public Enemy { public: void attack() { cout << "ninja attacks with power - " << attackPwr << endl; } void defense() { cout << "ninja defends " << endl; } }; class Monster: public Enemy { public: void attack() { cout << "monster attacks with power - " << attackPwr << endl; } void defense() { cout << "monster defends " << endl; } }; int main (){ cout << "Hello world" << endl; Ninja n; Monster m; n.attack(); m.attack(); Enemy *e1 = &n; Enemy *e2 = &m; e2 -> setPwr(20); e1 -> attack(); // error : 'class Enemy' has no member named 'attack'; did you mean 'attackPwr'? e2 -> attack(); return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long int ll; ll f(ll, ll); int main() { ll a, b; cin>>a>>b; cout<<f(a, b)<<endl; } ll f(ll a, ll b) { if(b==1) return a; if(!a) return 0; if(a>b) { ll n = a/b; if(n*b==a) n--; return f(a-n*b, b)+n; } else { ll n = (b/a); if(n*a==b) n--; return f(a, b-n*a)+n; } }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include "CObjectDetection.hpp" # include <Siv3D/Image.hpp> # include <Siv3D/OpenCV_Bridge.hpp> # include <Siv3D/FileSystem.hpp> # include <Siv3D/Compression.hpp> # include <Siv3D/Resource.hpp> # include <Siv3D/Logger.hpp> # include "../EngineDirectory/EngineDirectory.hpp" namespace s3d { namespace detail { static const FilePath CascadeNames[5] = { U"frontal_face_alt2.xml", U"eye.xml", U"eye_eyeglasses.xml", U"face_anime.xml", U"frontal_catface.xml", }; } CObjectDetection::CObjectDetection() { m_unavailable.fill(false); } CObjectDetection::~CObjectDetection() { } bool CObjectDetection::init() { const FilePath cascadeDirectory = EngineDirectory::CurrectVersionCommon() + U"objdetect/haarcascade/"; for (const auto& cascadeName : detail::CascadeNames) { const FilePath cascadeResourcePath = Resource(U"engine/objdetect/haarcascade/" + cascadeName + U".zst"); if (!FileSystem::Exists(cascadeDirectory + cascadeName) && FileSystem::Exists(cascadeResourcePath)) { Compression::DecompressFileToFile(cascadeResourcePath, cascadeDirectory + cascadeName); } } LOG_INFO(U"ℹ️ ObjectDetection initialized"); return true; } Array<Rect> CObjectDetection::detect(const Image& image, const HaarCascade cascade, const int32 minNeighbors, const Size& minSize, const Size& maxSize) { if (!m_initialized) { init(); } if (!image) { return{}; } const size_t cascadeIndex = static_cast<size_t>(cascade); if (m_unavailable[cascadeIndex]) { return{}; } if (image.width() != m_mat.cols || image.height() != m_mat.rows) { m_mat.create(image.height(), image.width()); } if (m_cascades[cascadeIndex].empty()) { if (!load(cascadeIndex)) { return{}; } } OpenCV_Bridge::ToGrayScale(image, m_mat); std::vector<cv::Rect> faces; m_cascades[cascadeIndex].detectMultiScale(m_mat, faces, 1.1, minNeighbors, 0, cv::Size(minSize.x, minSize.y), cv::Size(maxSize.x, maxSize.y)); Array<Rect> rects; for (const auto& face : faces) { rects.emplace_back(face.x, face.y, face.width, face.height); } return rects; } Array<Rect> CObjectDetection::detect(const Image& image, const HaarCascade cascade, const Array<Rect>& regions, const int32 minNeighbors, const Size& minSize, const Size& maxSize) { if (!m_initialized) { init(); } if (!image) { return{}; } const size_t cascadeIndex = static_cast<size_t>(cascade); if (m_unavailable[cascadeIndex]) { return{}; } if (image.width() != m_mat.cols || image.height() != m_mat.rows) { m_mat.create(image.height(), image.width()); } if (m_cascades[cascadeIndex].empty()) { if (!load(cascadeIndex)) { return{}; } } OpenCV_Bridge::ToGrayScale(image, m_mat); Array<Rect> rects; for (const auto& region : regions) { std::vector<cv::Rect> faces; const cv::Rect roi(region.x, region.y, region.w, region.h); m_cascades[cascadeIndex].detectMultiScale(m_mat(roi), faces, 1.1, minNeighbors, 0, cv::Size(minSize.x, minSize.y), cv::Size(maxSize.x, maxSize.y)); for (const auto& face : faces) { rects.emplace_back(face.x + region.x, face.y + region.y, face.width, face.height); } } return rects; } bool CObjectDetection::load(const size_t cascadeIndex) { const FilePath cascadeDirectory = EngineDirectory::CurrectVersionCommon() + U"objdetect/haarcascade/"; const FilePath path = cascadeDirectory + detail::CascadeNames[cascadeIndex]; if (!m_cascades[cascadeIndex].load(path.narrow())) { m_unavailable[cascadeIndex] = true; return false; } return true; } }
#ifndef prke_h_ #define prke_h_ #include "../Global/GlobalHeaders.h" #include "PRKE_Tools.h" class PRKE { public: // Constructor PRKE (unsigned int); // Destructor ~PRKE () {} void perform_prke_step(); void set_prke_parameters ( const vector<double>& time_reactivity_, const vector<double>& reactivity_, const vector<double>& beta_, const vector<double>& lambda_, const double& meanGenTime_, const double& timeStep_, const vector<double>& initial_solution_ ); // Accessors double get_sumBeta() {return sumBeta;} double get_meanGenTime() {return meanGenTime;} double get_timeStep() {return timeStep;} vector<double> get_lambda() {return lambda;} vector<double> get_beta() {return beta;} vector<double> get_time_reactivity() {return time_reactivity;} vector<double> get_reactivity() {return reactivity;} vector<double> get_solution() {return solution;} vector<double> get_old_solution() {return old_solution;} vector<double> get_initial_solution() {return initial_solution;} // Manipulators void set_beta(vector<double> beta_) {beta = beta_;} void set_sumBeta(double sumBeta_) {sumBeta = sumBeta_;} void set_lambda(vector<double> lambda_) {lambda = lambda_;} void set_meanGenTime(double meanGenTime_) {meanGenTime = meanGenTime_;} void set_timeStep(double timeStep_) {timeStep = timeStep_;} void set_smallTimeStep(double smallTimeStep_) {smallTimeStep = smallTimeStep_;} void set_time_reactivity(vector<double> time_reactivity_) {time_reactivity = time_reactivity_;} void set_reactivity(vector<double> reactivity_) {reactivity = reactivity_;} void set_solution(vector<double> solution_) {solution = solution_;} void set_old_solution(vector<double> old_solution_) {old_solution = old_solution_;} void set_initial_solution(vector<double> initial_solution_) {initial_solution = initial_solution_;} private: const unsigned int n_precursors; vector<double> reactivity; vector<double> time_reactivity; vector<double> lambda; vector<double> beta; vector<double> solution; vector<double> old_solution; vector<double> initial_solution; double sumBeta; double meanGenTime; double timeStep; double smallTimeStep; inline double interpolate_reactivity(double time); inline vector< vector<double>> create_A_matrix(unsigned int dim); inline void forward_euler_step(); inline void backward_euler_step(); inline void crank_nicholson_step(); }; // Accessors // Manipulators //Interpolate Reactivity Linearly double PRKE::interpolate_reactivity(double time) { unsigned int final = time_reactivity.size() - 1; if (reactivity.size() == 1) { return reactivity.front(); } else { if (time < time_reactivity.front()) { return reactivity.front() - (reactivity.at(1) - reactivity.front())/(time_reactivity.at(1) - time_reactivity.front())*(time_reactivity.front() - time); } else if (time > time_reactivity.back()) { return reactivity.back() - (reactivity.back() - reactivity.at(final - 1))/(time_reactivity.back() - time_reactivity.at(final - 1))*(time - time_reactivity.at(final - 1)); } else { for (unsigned int i=1; i<reactivity.size(); ++i) { if (time <= time_reactivity.at(i)) { return reactivity.at(i-1) + (reactivity.at(i) - reactivity.at(i-1))/(time_reactivity.at(i) - time_reactivity.at(i-1))*(time - time_reactivity.at(i-1)); } } } } }; //Create PRKE matrix vector< vector<double>> PRKE::create_A_matrix(unsigned int dim) { vector< vector<double>> AMat(dim, vector<double>(dim,0.0)); AMat.at(0).at(0) = (interpolate_reactivity(smallTimeStep) - sumBeta) / (meanGenTime); for (unsigned int i=1; i < n_precursors; ++i) { AMat.at(i).at(0) = beta.at(i-1) / meanGenTime; AMat.at(i).at(i) = -lambda.at(i-1); AMat.at(0).at(i) = lambda.at(i-1); } return AMat; }; //Forward Euler Step void PRKE::forward_euler_step() { vector< vector<double>> A = create_A_matrix(n_precursors + 1); vector< vector<double>> eye = PRKE_Tools::create_identity_matrix(n_precursors + 1); vector< vector<double>> tempMat = A; PRKE_Tools::multiply_by_scalar(&tempMat,smallTimeStep); tempMat = PRKE_Tools::matrix_addition(tempMat, eye); solution = PRKE_Tools::matrix_vector_multiplication(tempMat, old_solution); return; }; #endif
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CryptSimulation1d.hpp" #include "WntConcentration.hpp" #include "SmartPointers.hpp" CryptSimulation1d::CryptSimulation1d(AbstractCellPopulation<1>& rCellPopulation, bool deleteCellPopulationInDestructor, bool initialiseCells) : OffLatticeSimulation<1>(rCellPopulation, deleteCellPopulationInDestructor, initialiseCells) { mpStaticCastCellPopulation = static_cast<MeshBasedCellPopulation<1>*>(&mrCellPopulation); if (!mDeleteCellPopulationInDestructor) { // Pass a CryptSimulationBoundaryCondition object into mBoundaryConditions MAKE_PTR_ARGS(CryptSimulationBoundaryCondition<1>, p_bc, (&rCellPopulation)); AddCellPopulationBoundaryCondition(p_bc); } MAKE_PTR(CryptCentreBasedDivisionRule<1>, p_centre_div_rule); mpStaticCastCellPopulation->SetCentreBasedDivisionRule(p_centre_div_rule); } CryptSimulation1d::~CryptSimulation1d() { } void CryptSimulation1d::OutputSimulationParameters(out_stream& rParamsFile) { // No parameters to output // Call method on direct parent class OffLatticeSimulation<1>::OutputSimulationParameters(rParamsFile); } // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" CHASTE_CLASS_EXPORT(CryptSimulation1d)
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int num1, num2; printf("Ingresar el Primer numero:\n "); scanf("%d", &num1); printf("Ingresar el Segundo numero:\n "); scanf("%d", &num2); if (num1>num2) { printf("El Primer Numero es el mayor: %d \n", num1); } else { printf("El Segundo Numero es el mayor: %d \n", num2); } system("PAUSE"); return 0; }
#include <iostream> using namespace std; int main() { int score[3]; double aver = 0; for (int i = 0; i < 3; i++) { cin >> score[i]; aver += score[i]; } aver = aver / 3.0; cout << fixed; cout.precision(2); cout << aver << endl; if (aver >= 75) cout << 'A'; else if (aver >= 50) cout << 'B'; else cout << 'F'; }
#define MAXSIZE 5 #define LISTINCREMENT 10 #include<stdio.h> #include<stdlib.h> typedef struct{ int *elem; int length; int listsize; int incrementsize; }SqList; /*线性表的初始化操作*/ void InitList(SqList &myList , int maxsize , int incresize){ // 构造一个最大容量为maxsize的顺序表L myList.elem = new int[maxsize]; // 为顺序表分配一个最大容量为maxsize的数组空间 myList.length = 0; // 顺序表中当前所含元素个数为0 myList.listsize = maxsize; // 该顺序表可以容纳maxsize个数据元素 myList.incrementsize = incresize; // 需要时可扩容incresize个元素空间 printf("请输入你想要初始元素的个数<最大%d>:",maxsize); scanf("%d",&myList.length); if(myList.length > maxsize || myList.length < 0){ printf("你输入的长度有误!\n"); myList.length = 0; } else { printf("数字之间请用空格隔开:"); for( int i = 0 ; i < myList.length ; i++){ scanf("%d",&myList.elem[i]); } } } /*线性表的遍历*/ void ListTraverse(SqList myList){ if(myList.length == 0){ printf("表为空表!\n"); } else{ for ( int i = 0 ; i < myList.length; i++){ printf("%d ",myList.elem[i]); } printf("\n"); } } /*查找元素*/ int LocateElem(SqList myList , int e){ int location = 0; for( int i = 0 ; i <= myList.length ; i++){ if(myList.elem[i] == e){ location = i + 1; break; } } return location; /* // 课本算法 int i = 1; // 初始位序 int *p = myList.elem; // 指针p指向第一个元素的存储位置 while (i<=myList.length && *p++ != e){ // 依次遍历 ++i; // 找不到元素就把当前位序向后挪一位 } if (i<=myList.length){ return i; // 循环后,如果位序位于小于长度,即意味着找到了,并返回位序 }else { return 0; // 否则位序挪动到了长度的后面,即没找到。 } */ } /*追加扩容*/ void increment(SqList &myList){ int *p; p = new int[myList.listsize + myList.incrementsize]; // 定义一个int类型的指针,并指向一个临时数组的首地址 for ( int i = 0 ; i <= myList.length ; i++){ p[i] = myList.elem[i]; // 将当前的线性表中的数组数据全部迁移到临时数组中去 } delete[] myList.elem; // 删除当前的线性表中的数组 myList.elem = p; // 将刚才创建的临时数组移交给线性表的elem,使其成为线性表中的数组 myList.listsize = myList.listsize + myList.incrementsize; // 移交完毕后listsize应改变 printf("扩容成功:当前线性表的最大长度为%d\n" , myList.listsize); } /*插入元素*/ void ListInsert(SqList &myList , int loc , int e){ if( loc < 1 || loc > myList.length + 1){ printf("插入的位置有误!\n"); return ; } else if (myList.length == myList.listsize){ // 如果表满就扩容 increment(myList); } for( int i = myList.length - 1 ; i >= loc - 1 ; i--){ myList.elem[i+1] = myList.elem[i]; } myList.elem[loc-1] = e ; myList.length++; } /*删除元素*/ bool ListDelete(SqList &myList , int loc , int &e){ if(myList.length == 0){ printf("表为空,无法删除!\n"); return false; } if( loc < 1 || loc > myList.length){ printf("删除的位置有误!\n"); return false; } e = myList.elem[loc-1]; for(int i = loc - 1 ; i <= myList.length -1 ; i++){ myList.elem[i] = myList.elem[i+1]; } myList.length--; return true; } void DestroyList(SqList &myList){ delete[] myList.elem; myList.listsize = 0; myList.length = 0; } /*功能菜单*/ void menu(SqList &myList){ printf("\n"); printf("-----功能-----\n"); printf("1 -----> 创建线性表\n"); printf("2 -----> 遍历线性表\n"); printf("3 -----> 查找元素\n"); printf("4 -----> 追加扩容\n"); printf("5 -----> 插入元素\n"); printf("6 -----> 删除元素\n"); printf("7 -----> 销毁线性表\n"); printf("0 -----> 退出\n"); printf("\n"); int f; printf("请输入选项:"); scanf("%d",&f); switch(f){ case 1: // 创建线性表 InitList(myList , MAXSIZE , LISTINCREMENT); break; case 2: // 遍历线性表 ListTraverse(myList); printf("当前线性表的长度为:%d,最大长度为:%d\n",myList.length , myList.listsize); break; case 3: // 查找元素测试 int e; printf("请输入要查找的元素:"); scanf("%d",&e); int location ; location = LocateElem(myList,e); if(location){ printf("元素 %d 第一次出现的位置为:%d\n",e,location); }else{ printf("元素%d不存在\n",e); } break; case 4: increment(myList); break; case 5: int e_insert; int loc_insert; printf("请输入你要插入的元素:"); scanf("%d" , &e_insert); printf("请输入你要插入的位置:"); scanf("%d" , &loc_insert); ListInsert(myList , loc_insert , e_insert); break; case 6: int e_delete; int loc_delete; printf("请输入你要删除的位置:"); scanf("%d" , &loc_delete); if(ListDelete(myList , loc_delete , e_delete)){ printf("删除成功:删除的元素为%d\n" , e_delete); } break; case 7: DestroyList(myList); break; case 0: exit(0); break; default: break; } } int main(){ SqList myList; while (true){ menu(myList); } }
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_BA_GCP_CONSTRAINED_JACOBIAN_MATRIX_HPP_ #define _HS_SFM_BUNDLE_ADJUSTMENT_BA_GCP_CONSTRAINED_JACOBIAN_MATRIX_HPP_ #include "hs_sfm/bundle_adjustment/ba_naive_jacobian_matrix.hpp" namespace hs { namespace sfm { namespace ba { template <typename _Scalar, typename _Index, _Index params_per_feature, _Index params_per_camera, _Index params_per_point> class BAGCPConstrainedJacobianMatrix { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef _Index Index; typedef BANaiveJacobianMatrix<Scalar, Index, params_per_feature, params_per_camera, params_per_point> NaiveJacobianMatrix; public: inline NaiveJacobianMatrix& naive_jacobian_matrix() { return naive_jacobian_matrix_; } inline const NaiveJacobianMatrix& naive_jacobian_matrix() const { return naive_jacobian_matrix_; } inline Index number_of_gcps() const { return number_of_gcps_; } inline void set_number_of_gcps(Index number_of_gcps) { number_of_gcps_ = number_of_gcps; } Scalar coeff(Index i, Index j) const { Index y_feature_size = naive_jacobian_matrix_.camera_derivatives().size() * params_per_feature; Index naive_x_size = naive_jacobian_matrix_.number_of_cameras() * params_per_camera + (naive_jacobian_matrix_.number_of_points() - number_of_gcps_) * params_per_point; if (i < y_feature_size) { return naive_jacobian_matrix_.coeff(i, j); } else if ((i - y_feature_size) == (j - naive_x_size)) { return Scalar(1); } else { return Scalar(0); } } private: NaiveJacobianMatrix naive_jacobian_matrix_; Index number_of_gcps_; }; } } } #endif
#include <whiskey/Printing/Printer.hpp> #include <whiskey/AST/Node.hpp> namespace whiskey { const unsigned int Printer::defaultTabWidth = 2; void Printer::printNewline(std::ostream &os, unsigned int indent) { os << "\n"; for (unsigned int i = 0; i < indent * tabWidth; i++) { os << ' '; } } Printer::Printer(bool usePrecedence, unsigned int tabWidth) : usePrecedence(usePrecedence), tabWidth(tabWidth) { } Printer::~Printer() { } bool Printer::getUsePrecedence() const { return usePrecedence; } void Printer::setUsePrecedence(bool value) { usePrecedence = value; } unsigned int Printer::getTabWidth() const { return tabWidth; } void Printer::setTabWidth(unsigned int value) { tabWidth = value; } void Printer::print(std::ostream &os, const Node &node, unsigned int indent, Precedence outer) { bool np = false; if (usePrecedence) { np = needsParenthesis(getPrecedence(node.getType()), outer); } if (np) { os << "("; } onPrint(os, node, indent); if (np) { os << ")"; } } } // namespace whiskey
/** * * @file Buffer.cpp * @author NaokiTakahashi * **/ #include "Buffer.hpp" #include <stdexcept> #include <algorithm> #include <Tools/Math/Matrix.hpp> #include "TimeSeriesData.hpp" namespace RobotStatus { template <typename T> Buffer<T>::Buffer(const SizeType &maximum_data_size) { resize(maximum_data_size); } template <typename T> void Buffer<T>::resize(const SizeType &maximum_data_size) { if(0 >= maximum_data_size) { throw std::out_of_range("Data size too small from RobotStatus::Buffer::resize"); } this->maximum_data_size = maximum_data_size; reset(); } template <typename T> void Buffer<T>::reset() { if(data_list) { data_list->clear(); } data_list = std::make_unique<Data>(maximum_data_size); data_iterator = std::unique_ptr<Iterator>(); *data_iterator = data_list->begin(); } template <typename T> void Buffer<T>::push(const T &data) { std::advance(*data_iterator, 1); if(*data_iterator >= data_list->end()) { *data_iterator = data_list->begin(); } **data_iterator = data; } template <typename T> typename Buffer<T>::SizeType Buffer<T>::size() { return data_list->size(); } template <typename T> T &Buffer<T>::at(const SizeType &n) { if(maximum_data_size < n || 0 > n) { throw std::out_of_range("Illegal access from RobotStatus::Buffer::at"); } static SizeType current_n; current_n = std::distance(data_list->begin(), *data_iterator); if(n > current_n) { return data_list->at(current_n + maximum_data_size - n); } return data_list->at(current_n - n); } template <typename T> typename Buffer<T>::Data Buffer<T>::get_raw_data() { return *data_list; } template <typename T> typename Buffer<T>::Data Buffer<T>::get_sorted_datas() { auto return_data = *data_list; std::sort(return_data.begin(), return_data.end()); return return_data; } template class Buffer<int>; template class Buffer<float>; template class Buffer<double>; template class Buffer<TimeSeriesData<int>>; template class Buffer<TimeSeriesData<float>>; template class Buffer<TimeSeriesData<double>>; template class Buffer<TimeSeriesData<Tools::Math::VectorX<int>>>; template class Buffer<TimeSeriesData<Tools::Math::VectorX<float>>>; template class Buffer<TimeSeriesData<Tools::Math::VectorX<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector2<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector2<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector2<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector3<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector3<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector3<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector4<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector4<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Vector4<double>>>; template class Buffer<TimeSeriesData<Tools::Math::MatrixX<int>>>; template class Buffer<TimeSeriesData<Tools::Math::MatrixX<float>>>; template class Buffer<TimeSeriesData<Tools::Math::MatrixX<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix2<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix2<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix2<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix3<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix3<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix3<double>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix4<int>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix4<float>>>; template class Buffer<TimeSeriesData<Tools::Math::Matrix4<double>>>; }
#include <iostream> #include <cmath> using namespace std; int main() { int r1, r2, number, num1, num2, count = 0; cout << "Enter the number you want to check: "; cin >> number; num1 = number; num2 = number; while (num1 > 0) { r1 = num1 % 10; while (num2 > 0) { r2 = num2 % 10; if (r1 == r2) { count++; } num2 = num2 / 10; } num1 = num1 / 10; } if (count == 1) { cout << "The number is unique."; } else { cout << "The number is not unique."; } }
void Solution::merge(vector<int> &a, vector<int> &b) { int n=a.size(); int m=b.size(); int i=n-1,j=m-1; int l=m+n-1; a.resize(m+n); while(j>=0) { if(i>=0 and a[i]>b[j]) { a[l--]=a[i--]; } else { a[l--]=b[j--]; } } }
#include "Base/SlideCore.h" SlideCore::SlideCore():Matrix() { //ctor } SlideCore::SlideCore(int Row,int Col):Matrix(Row,Col),EmptyCell(Row-1,Col-1) { int p = 1; for(int i = 0;i<Row;i++) for(int j = 0; j< Col; j++) (*this)[i][j] = p++; (*this)[Row-1][Col-1] = 0; } void SlideCore::Move(Direction D) { switch(D) { case Direction::Up: //cout<<" Up Requested "<<endl; if(EmptyCell.i + 1 <= Row-1) { //cout<<" I passed check for up"<<endl; Swap(Data[EmptyCell.i][EmptyCell.j],Data[EmptyCell.i+1][EmptyCell.j]); EmptyCell.i++; } break; case Direction::Down: //cout<<" down requested "<<endl; if(EmptyCell.i - 1 >= 0) { //cout<<" I passed for down "<<endl; Swap(Data[EmptyCell.i][EmptyCell.j],Data[EmptyCell.i-1][EmptyCell.j]); EmptyCell.i--; } break; case Direction::Left: ////cout<<"I left "<<endl; if(EmptyCell.j + 1 <= Col-1) { //cout<<" I passed check for LEft"<<endl; Swap(Data[EmptyCell.i][EmptyCell.j],Data[EmptyCell.i][EmptyCell.j+1]); EmptyCell.j++; } break; case Direction::Right: //cout<<" Right requested "<<endl; if(EmptyCell.j - 1 >= 0) { //cout<<" I passed for right "<<endl; Swap(Data[EmptyCell.i][EmptyCell.j],Data[EmptyCell.i][EmptyCell.j-1]); EmptyCell.j--; } break; } } int SlideCore::GetVal(int Row,int Col) { return Data[Row][Col]; } bool SlideCore::operator==(SlideCore TestCore) { if(Row != TestCore.Row or Col != TestCore.Col) { return false; } else { for(int row =0; row<Row; row++) for(int col = 0; col<Col; col++) if(Data[row][col] != TestCore[row][col]) return false; } return true; } vector<Direction> SlideCore::PossibleMoves() { vector<Direction> Moves; if(EmptyCell.i == 0) Moves.push_back(Direction::Up); if(EmptyCell.i > 0 and EmptyCell.i < Row - 1) { Moves.push_back(Direction::Down); Moves.push_back(Direction::Up); } if(EmptyCell.i == Row - 1) Moves.push_back(Direction::Down); if(EmptyCell.j == 0) Moves.push_back(Direction::Left); if(EmptyCell.j > 0 and EmptyCell.j < Col - 1) { Moves.push_back(Direction::Right); Moves.push_back(Direction::Left); } if(EmptyCell.j == Col - 1) Moves.push_back(Direction::Right); return Moves; } vector<SlideCore> SlideCore::MakeMoves(vector<Direction> Moves) { vector<SlideCore> Children; Children.reserve(Moves.size()); for(auto MoveDirection:Moves) { SlideCore Current(*this); Current.Move(MoveDirection); Children.push_back(Current); } return Children; } vector<SlideCore> SlideCore::MakeAllMoves() { vector<Direction> Moves = this->PossibleMoves(); return this->MakeMoves(Moves); } SlideCore SlideCore::MakeOneMove(Direction CurrentMove) { SlideCore Current(*this); Current.Move(CurrentMove); return Current; } /* vector<Direction> SlideCore::PossibleMoves() { if(EmptyCell.i == 0) { if(EmptyCell.j == 0) { vector<Direction> ReturnValue = {Direction::Up,Direction::Left}; return ReturnValue; } else if(EmptyCell.j > 0 and EmptyCell.j < Col-1) { vector<Direction> ReturnValue = {Direction::Up,Direction::Left, Direction::Down}; return ReturnValue; } else if(EmptyCell.j = Col-1) { vector<Direction> ReturnValue = {Direction::Down,Direction::Left}; return ReturnValue; } } if(EmptyCell.i >0 and EmptyCell.i < Row - 1) { if(EmptyCell.j == 0) { vector<Direction> ReturnValue = {Direction::Up,Direction::Left,Direction::Right}; return ReturnValue; } else if(EmptyCell.j >0 and EmptyCell.j < Col-1) { vector<Direction> ReturnValue = {Direction::Up,Direction::Left,Direction::Right,Direction::Down}; return ReturnValue; } else if(EmptyCell.j = Col-1) { vector<Direction> ReturnValue = {Direction::Right,Direction::Left,Direction::Down}; return ReturnValue; } } if(EmptyCell.i == Row-1) { if(EmptyCell.j == 0) { vector<Direction> ReturnValue = {Direction::Up,Direction::Right}; return ReturnValue; } else if(EmptyCell.j >0 and EmptyCell.j < Col-1) { vector<Direction> ReturnValue = {Direction::Up,Direction::Right,Direction::Down}; return ReturnValue; } else if(EmptyCell.j = Col-1) { vector<Direction> ReturnValue = {Direction::Down,Direction::Right}; return ReturnValue; } } } */
#include<bits/stdc++.h> using namespace std; int main(){ int m,n,d,s,e; cin>>m>>n; d=m; s=m; while(d>=n){ d=m/n; e=m%n; s=s+d; d=d+e; m=d; } cout<<s; return 0; }
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> // Common file #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update using namespace std; using namespace __gnu_pbds; double INF = 1e100; double EPS = 1e-12; typedef long long int ll; typedef pair < int,int > PII; typedef pair < ll,ll > PLL; typedef tree< int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define F first #define S second ostream& operator<<(ostream & os, PLL h){ return os << "( " << h.F << ", " << h.S << " )" << endl; } PLL operator+ (PLL a, ll x) {return {a.F + x, a.S + x} ;} PLL operator- (PLL a, ll x) {return {a.F - x, a.S - x} ;} PLL operator* (PLL a, ll x) {return {a.F * x, a.S * x} ;} PLL operator+(PLL x, PLL y) { return {x.F + y.F,x.S + y.S} ;} PLL operator-(PLL x,PLL y) { return {x.F - y.F, x.S - y.S} ;} PLL operator*(PLL x,PLL y) { return {x.F * y.F , x.S * y.S} ;} PLL operator%(PLL x,PLL y) { return {x.F % y.F, x.S % y.S} ;} ll const MOD = 1e9 + 7; ll bigmod(ll a, ll b){ if(!b) return 1; ll x = bigmod(a,b/2); x = (x * x)%MOD; if(b&1) x = (x * a) %MOD; return x; } vector < ll > primes; vector < bool > marks; void sieve(int n) { marks.resize(n+10,0); marks[1] = 1; for(int i = 2; i < n; i++){ if(!marks[i]){ for(int j = 2*i; j < n; j += i){ marks[j] = 1; } primes.push_back(i); } } } int const N = 5e5 + 10; vector<int> g[N]; vector<int> path; vector<int> dep[N]; vector<bool>mark(N,false); int n,m; void clean(int n){ for(int i = 0; i <= n; i++) { g[i].clear(); dep[i].clear(); } path.clear(); fill(mark.begin(), mark.begin() + n + 2, false); } bool dfs(int u,int d){ path.push_back(u); if(path.size() * 2 >= n){ return 1; // wait there buddy } mark[u] = 1; dep[d].push_back(u); bool done = 0; for(auto v : g[u]){ if(!mark[v]){ if(!done){ done |= dfs(v,d+1); } } } if(!done) path.pop_back(); return done; } void solve() { cin >> n >> m; for(int i = 0; i < m; i++){ int a,b; cin >> a >> b; g[a].push_back(b); g[b].push_back(a); } //cerr << "Hello" << endl; if( dfs(1,0) ){ cout << "PATH" << '\n'; cout << path.size() << '\n'; for(auto x : path) { cout << x << " " ; } cout << "\n" ; } else { vector<PII> pairs; for(int i = 0; i < n; i++){ while(dep[i].size() >= 2){ int t1 = dep[i].back(); dep[i].pop_back(); int t2 = dep[i].back(); dep[i].pop_back(); pairs.push_back({t1,t2}); } } cout << "PAIRING" << '\n'; cout << pairs.size() << '\n'; for(auto x : pairs){ cout << x.first << " " << x.second << '\n'; } } clean(n); } int main(){ ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--){ solve(); } return 0; }
#ifndef BEXP_IC_TRANSLATOR_H #define BEXP_IC_TRANSLATOR_H #include "treevisitor.h" #include "ictranslator.h" #include "labelset.h" #include "../symboltable.h" #include "../instructions/instructions.h" #include "../instructions/gotoi.h" #include "../instructions/ifi.h" #include "../instructions/varregister.h" #include "../syntaxtree/number.h" #include "../syntaxtree/binop.h" using namespace std; //forward references class ICTranslator; class Variable; class Function; class Array; class Block; class IfStatement; class WhileStatement; class Assignment; class ReturnStatement; class Funcall; class ReadStatement; class WriteStatement; class UnaryOp; class BinaryOp; class Number; class QChar; class LengthExpression; class ArrayAccess; /** * An Itermediate Code translator which translates only boolean expressions, * ie expressions used as conditions in if and while statements. * It translates the boolean binary operators by flow of control, rather than * an ICOpTranslator which translates them by value. */ class BexpTranslator: public TreeVisitor, public OperatorVisitor { public: /** * create a new BexpTranslator * @param parent the ICTranslator who spawned this BexpTranslator to * translate his if or while statement */ BexpTranslator(ICTranslator* parent): parent_ (parent), trueSet_ (new LabelSet), falseSet_(new LabelSet), zero_ (new Number(0)) { } ~BexpTranslator(); LabelSet& trueSet() const { return *trueSet_; } LabelSet& falseSet() const { return *falseSet_; } /** * var * translates to * code testing whether the value is zero or not */ virtual void visitVariable(Variable* var); /** * f(exp1,exp2,exp3) * translates to * code testing whether the returnvalue * of the function is zero or not */ virtual void visitFuncall(Funcall* funcall); /** * op exp * translates to * code testing whether (op exp) is true or not * (if the operator is NOT, this method will just * switch the true and false sets) */ virtual void visitUnaryOp(UnaryOp* unop); /** * exp1 op exp2 * translates to * code testing whether the result is zero or not */ virtual void visitBinaryOp(BinaryOp* binop); /** * num * translates to * code testing whether num is zero or not */ virtual void visitNumber(Number* num); /** * char * translates to * code testing whether char is zero or not */ virtual void visitQChar(QChar* chr); /** * length exp * translates to * code testing whether the result is zero or not */ virtual void visitLengthExpression(LengthExpression* len); /** * a[exp1,...,expn] * translates to * code testing whether the result is zero or not */ virtual void visitArrayAccess(ArrayAccess* arrayaccess); //inherited from operatorvisitor: //arithmetic operations will be generated 'by value' //boolean operations will be generated 'by flow of control' (in-line) virtual void visitDividesOp(DividesOp* op); virtual void visitEqualOp(EqualOp* op); virtual void visitGreaterOp(GreaterOp* op); virtual void visitLessOp(LessOp* op); virtual void visitMinusOp(MinusOp* op); virtual void visitNEqualOp(NEqualOp* op); virtual void visitPlusOp(PlusOp* op); virtual void visitTimesOp(TimesOp* op); private: /** * Generates code for an arithmetic binary operation like +,*,... */ void generateArithmeticBinop(); /** * Generates code for a boolean binary operation like <,==,... * This can be done 'in-line' in the if statement (by flow of control) */ void generateBooleanBinop(); /** * Indicates the next instruction's label must be added * to the true set */ void nextInstrTrue(); /** * Indicates the next instruction's label must be added * to the false set */ void nextInstrFalse(); /** * Generate a new register containing 0 */ NumRegister* generateZero() const; /** * Generate code that checks whether the given * register contains 0 or not */ void generateZeroTest(VarRegister* var); /** * Generate code for a jump instruction with * yet unknown destination */ void generateZeroJump(); ICTranslator* parent_; LabelSet* trueSet_; LabelSet* falseSet_; Number* zero_; BinaryOp* currentBinop_; }; #endif
#include "pch.h" #include "Rasterizer.h" #include "algorithm" #include "ppl.h" using namespace DirectX; using namespace GameEngine; Rasterizer::Rasterizer() { } void Rasterizer::SetFrameBuffer(byte* buffer, unsigned int width, unsigned int height) { m_buffer = buffer; m_pixelWidth = width; m_pixelHeight = height; zbuffer = std::vector<double>(height * width, 1.0); m_mutexBuffer = new std::mutex[width * height]; } void Rasterizer::Clear() { memset(m_buffer, 0, 4 * m_pixelHeight * m_pixelWidth); zbuffer.assign(zbuffer.size(), 1.0); } void Rasterizer::SetPixel(unsigned int x, unsigned int y, const Color &color) { if (x >= m_pixelWidth || y >= m_pixelHeight || x < 0 || y < 0) return; ByteColor byteColor = color.ToByte(); std::lock_guard<std::mutex> locker(m_mutexBuffer[y * m_pixelHeight + x]); m_buffer[(y * m_pixelWidth + x) * 4] = byteColor.B; m_buffer[(y * m_pixelWidth + x) * 4 + 1] = byteColor.G; m_buffer[(y * m_pixelWidth + x) * 4 + 2] = byteColor.R; m_buffer[(y * m_pixelWidth + x) * 4 + 3] = byteColor.A; } void Rasterizer::SetPixel(float x, float y, const Color &color) { if (x < 0.0f || y < 0.0f) return; SetPixel((unsigned int)x, (unsigned int)y, color); } void Rasterizer::SetPixel(unsigned int x, unsigned int y, double z, const Color &color) { if (x < m_pixelWidth && y < m_pixelHeight && x >= 0 && y >= 0) { if (zbuffer[y * m_pixelWidth + x] < z) { return; } zbuffer.at(y * m_pixelWidth + x) = z; } SetPixel(x, y, color); } float Rasterizer::ComputeLightIntensity(XMFLOAT3 dotLight, XMFLOAT3 vertex, XMFLOAT3 normal) { // Compute cosin between light's direction and normal XMVECTOR lightVec = XMLoadFloat3(&dotLight); XMVECTOR vertexVec = XMLoadFloat3(&vertex); XMVECTOR normalVec = XMVector3Normalize(XMLoadFloat3(&normal)); XMVECTOR lightDir = XMVector3Normalize(lightVec - vertexVec); return max(0.f, XMVector3Dot(normalVec, lightDir).m128_f32[0]); } Point XM_CALLCONV Rasterizer::Project(const Vertex& vertex, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { Point ret; XMVECTOR worldPosVec = XMVector3TransformCoord(XMLoadFloat3(&vertex.position), worldMatrix * viewMatrix * projectMatrix); XMFLOAT3 worldPos; XMStoreFloat3(&worldPos, worldPosVec); XMVECTOR worldNormalVec; worldNormalVec = XMVector3TransformCoord(XMLoadFloat3(&vertex.normal), worldMatrix * viewMatrix * projectMatrix); XMFLOAT3 worldNormal; XMStoreFloat3(&worldNormal, worldNormalVec); if (m_light != nullptr) { ret.lightIntensity = ComputeLightIntensity(m_light->GetDotLight(), worldPos, worldNormal); } else { ret.lightIntensity = 1.f; } ret.screenPos.x = worldPos.x * m_pixelWidth + m_pixelWidth / 2.0f; ret.screenPos.y = -worldPos.y * m_pixelHeight + m_pixelHeight / 2.0f; ret.screenPos.z = worldPos.z; ret.texCoord = vertex.texCoord; ret.color = vertex.color; return ret; } void Rasterizer::Paint(const Color &color) { for (unsigned int y = 0; y < m_pixelHeight; y += 1) { for (unsigned int x = 0; x < m_pixelWidth; x += 1) { SetPixel(x, y, color); } } } void Rasterizer::DrawLine(const Point &p1, const Point &p2, Texture* texture) { // Copy the parameters. int x1 = static_cast<int>(p1.screenPos.x); int y1 = static_cast<int>(p1.screenPos.y); XMFLOAT2 texCoor1 = p1.texCoord; float lightIntensity1 = p1.lightIntensity; double z1 = p1.screenPos.z; int x2 = static_cast<int>(p2.screenPos.x); int y2 = static_cast<int>(p2.screenPos.y); double z2 = p2.screenPos.z; XMFLOAT2 texCoor2 = p2.texCoord; float lightIntensity2 = p2.lightIntensity; Color color1 = p1.color; Color color2 = p2.color; Color color = color1; Color textureColor = Color(); float dotLightIntensity = 1.f; if (x1 == x2 && y1 == y2) { if (texture != nullptr) { textureColor = texture->Map(p1.texCoord.x, p1.texCoord.y); } if (m_light != nullptr) { dotLightIntensity = lightIntensity1; } SetPixel(x1, y1, z1, color * textureColor * dotLightIntensity); return; } if (x1 == x2) { if (y1 > y2) { std::swap(y1, y2); std::swap(z1, z2); std::swap(color1, color2); std::swap(texCoor1, texCoor2); std::swap(lightIntensity1, lightIntensity2); } Color colorStep = (color2 - color1) * (1.f / (y2 - y1)); float lightStep = (lightIntensity2 - lightIntensity1) / (y2 - y2); XMFLOAT2 texCoorStep = XMFLOAT2((texCoor2.x - texCoor1.x) / (y2 - y1), (texCoor2.y - texCoor1.y) / (y2 - y1)); color = color1; dotLightIntensity = lightIntensity1; XMFLOAT2 tempTexCoor = texCoor1; double zstep = (z2 - z1) * (1.f / (y2 - y1)); double z = z1; for (int i = y1; i < y2; ++i) { if (texture != nullptr) { textureColor = texture->Map(tempTexCoor.x, tempTexCoor.y); } SetPixel(x1, i, z, color * textureColor * dotLightIntensity); color = color + colorStep; if (m_light != nullptr) { dotLightIntensity += lightStep; } tempTexCoor = XMFLOAT2(tempTexCoor.x + texCoorStep.x, tempTexCoor.y + texCoorStep.y); z += zstep; } } else if (y1 == y2) { if (x1 > x2) { std::swap(x1, x2); std::swap(z1, z2); std::swap(color1, color2); std::swap(texCoor1, texCoor2); std::swap(lightIntensity1, lightIntensity2); } Color colorStep = (color2 - color1) * (1.f / (x2 - x1)); float lightStep = (lightIntensity2 - lightIntensity1) / (x2 - x1); XMFLOAT2 texCoorStep = XMFLOAT2((texCoor2.x - texCoor1.x) / (x2 - x1), (texCoor2.y - texCoor1.y) / (x2 - x1)); color = color1; dotLightIntensity = lightIntensity1; XMFLOAT2 tempTexCoor = texCoor1; double zstep = (z2 - z1) * (1.f / (x2 - x1)); double z = z1; for (int i = x1; i < x2; ++i) { if (texture != nullptr) { textureColor = texture->Map(tempTexCoor.x, tempTexCoor.y); } SetPixel(i, y1, z, color * textureColor * dotLightIntensity); color = color + colorStep; if (m_light != nullptr) { dotLightIntensity += lightStep; } tempTexCoor = XMFLOAT2(tempTexCoor.x + texCoorStep.x, tempTexCoor.y + texCoorStep.y); z += zstep; } } else { // Caculate the origin steep(or called slope) float xdiff = static_cast<float>(x2 - x1); float ydiff = static_cast<float>(y2 - y1); float steep = std::abs(ydiff / xdiff); if (steep > 1) { // Swap x and y. std::swap(x1, y1); std::swap(x2, y2); } if (x2 < x1) { // If x2 < x1, swap the direction of the line. std::swap(x1, x2); std::swap(y1, y2); std::swap(z1, z2); std::swap(color1, color2); std::swap(texCoor1, texCoor2); std::swap(lightIntensity1, lightIntensity2); } xdiff = static_cast<float>(x2 - x1); ydiff = static_cast<float>(y2 - y1); float slope = std::abs(ydiff / xdiff); int ystep = ydiff > 0 ? 1 : -1; double zstep = (z2 - z1) * (1.f / (x2 - x1)); float error = 0.f; int y = y1; Color colorStep = (color2 - color1) * (1.f / (x2 - x1)); float lightStep = (lightIntensity2 - lightIntensity1) / (x2 - x1); XMFLOAT2 texCoorStep = XMFLOAT2((texCoor2.x - texCoor1.x) / (x2 - x1), (texCoor2.y - texCoor1.y) / (x2 - x1)); color = color1; dotLightIntensity = lightIntensity1; XMFLOAT2 tempTexCoor = texCoor1; double z = z1; for (int x = x1; x < x2; ++x) { if (texture != nullptr) { textureColor = texture->Map(tempTexCoor.x, tempTexCoor.y); } z += zstep; error += slope; if (std::abs(error) > 0.5f) { y += ystep; error -= 1; } if (steep > 1) { SetPixel(y, x, z, color * textureColor * dotLightIntensity); } else { SetPixel(x, y, z, color * textureColor * dotLightIntensity); } color = color + colorStep; if (m_light != nullptr) { dotLightIntensity += lightStep; } tempTexCoor = XMFLOAT2(tempTexCoor.x + texCoorStep.x, tempTexCoor.y + texCoorStep.y); } } } void Rasterizer::DrawTriangle(Point p1, Point p2, Point p3, Texture* texture) { // Make sure that p1.screenPos.y < p2.screenPos.y < p3.screenPos.y SortTrianglePoints(p1, p2, p3); int x1 = static_cast<int>(p1.screenPos.x); int y1 = static_cast<int>(p1.screenPos.y); float lightIntensity1 = p1.lightIntensity; int x2 = static_cast<int>(p2.screenPos.x); int y2 = static_cast<int>(p2.screenPos.y); float lightIntensiry2 = p2.lightIntensity; int x3 = static_cast<int>(p3.screenPos.x); int y3 = static_cast<int>(p3.screenPos.y); float lightIntensity3 = p3.lightIntensity; //int x4 = 0; int y4 = 0; Color colorStep13 = Color(); Color colorStep12 = Color(); float lightStep13 = 0.f; float lightStep12 = 0.f; XMFLOAT2 texCoordStep13 = XMFLOAT2(); XMFLOAT2 texCoordStep12 = XMFLOAT2(); float scanX1 = 0.f; float scanX2 = 0.f; double scanZ1 = 0.f; double scanZ2 = 0.f; float invslope12 = 0.f; float invslope13 = 0.f; double depthInvslope12 = 0.f; double depthInvslope13 = 0.f; // Divide the triangle into 2 parts if (y3 - y1 != 0 ) { y4 = y2; //x4 = (y4 - y1) * (x3 - x1) / (y3 - y1) + x1; //double z4 = (y4 - y1) * (p3.screenPos.z - p1.screenPos.z) / (y3 - y1) + p1.screenPos.z; colorStep13 = (p3.color - p1.color) * (1 / (y3 - y1)); lightStep13 = (p3.lightIntensity - p1.lightIntensity) / (y3 - y1); texCoordStep13 = XMFLOAT2((p3.texCoord.x - p1.texCoord.x) / (y3 - y1), (p3.texCoord.y - p1.texCoord.y) / (y3 - y1)); float xdiff13 = static_cast<float>(x3 - x1); float ydiff13 = static_cast<float>(y3 - y1); double depthDiff13 = p3.screenPos.z - p1.screenPos.z; invslope13 = xdiff13 / ydiff13; depthInvslope13 = depthDiff13 / ydiff13; // The top triangle // if (y2 - y1 != 0) { colorStep12 = (p2.color - p1.color) * (1 / (y2 - y1)); XMFLOAT2 texCoordStep12 = XMFLOAT2((p2.texCoord.x - p1.texCoord.x) / (y2 - y1), (p2.texCoord.y - p1.texCoord.y) / (y2 - y1)); XMFLOAT2 texCoor4(texCoordStep13.x * (y4 - y1), texCoordStep13.y * (y4 - y1)); float xdiff12 = static_cast<float>(x2 - x1); float ydiff12 = static_cast<float>(y2 - y1); double depthDiff12 = p2.screenPos.z - p1.screenPos.z; invslope12 = xdiff12 / ydiff12; depthInvslope12 = depthDiff12 / ydiff12; scanX1 = static_cast<float>(x1); scanX2 = static_cast<float>(x1); scanZ1 = p1.screenPos.z; scanZ2 = p1.screenPos.z; Color color14 = p1.color; Color color12 = p1.color; float light14 = p1.lightIntensity; float light12 = p1.lightIntensity; XMFLOAT2 texCoord14 = p1.texCoord; XMFLOAT2 texCoord12 = p1.texCoord; for (int i = y1; i < y2; ++i) { Point lineStart = { XMFLOAT3(scanX1, (float)i, (float)scanZ1), light12, texCoord12, color12 }; Point lineEnd = { XMFLOAT3(scanX2, (float)i, (float)scanZ2), light14, texCoord14, color14 }; DrawLine(lineStart, lineEnd, texture); scanX1 += invslope12; scanX2 += invslope13; scanZ1 += depthInvslope12; scanZ2 += depthInvslope13; color12 = color12 + colorStep12; color14 = color14 + colorStep13; light12 += lightStep12; light14 += lightStep13; texCoord12 = XMFLOAT2(texCoord12.x + texCoordStep12.x, texCoord12.y + texCoordStep12.y); texCoord14 = XMFLOAT2(texCoord14.x + texCoordStep13.x, texCoord14.y + texCoordStep13.y); } } // Draw the lower triangle if (y3 - y2 != 0) { float xdiff23 = x3 - x2; float ydiff23 = y3 - y2; Color colorStep23 = (p3.color - p2.color) * (1 / ydiff23); float lightStep23 = (p3.lightIntensity - p2.lightIntensity) / ydiff23; XMFLOAT2 texCoordStep23 = XMFLOAT2((p3.texCoord.x - p2.texCoord.x) / ydiff23, (p3.texCoord.y - p2.texCoord.y) / ydiff23); double depthDiff23 = p3.screenPos.z - p2.screenPos.z; float invslop23 = xdiff23 / ydiff23; double depthInvslope23 = depthDiff23 / ydiff23; scanX1 = x3; scanX2 = x3; scanZ1 = p3.screenPos.z; scanZ2 = p3.screenPos.z; Color color34 = p3.color; Color color32 = p3.color; float light34 = p3.lightIntensity; float light32 = p3.lightIntensity; XMFLOAT2 texCoor34 = p3.texCoord; XMFLOAT2 texCoor32 = p3.texCoord; for (int i = y3; i > y2 - 1; --i) { Point lineStart = { XMFLOAT3(scanX1, (float)i, (float)scanZ1), light32, texCoor32, color32 }; Point lineEnd = { XMFLOAT3(scanX2, (float)i, (float)scanZ2), light34, texCoor34, color34 }; DrawLine(lineStart, lineEnd, texture); scanX1 -= invslop23; scanX2 -= invslope13; scanZ1 -= depthInvslope23; scanZ2 -= depthInvslope13; color34 = color34 - colorStep13; color32 = color32 - colorStep23; light32 -= lightStep23; light34 -= lightStep13; texCoor32 = XMFLOAT2(texCoor32.x - texCoordStep23.x, texCoor32.y - texCoordStep23.y); texCoor34 = XMFLOAT2(texCoor34.x - texCoordStep13.x, texCoor34.y - texCoordStep13.y); } } } } void Rasterizer::SortTrianglePoints(Point &pt1, Point &pt2, Point &pt3) { Point points[] = { pt1, pt2, pt3 }; std::sort(points, points + 3, [](Point p1, Point p2){ return p1.screenPos.y < p2.screenPos.y; }); pt1 = points[0]; pt2 = points[1]; pt3 = points[2]; } void XM_CALLCONV Rasterizer::RenderMeth(const Mesh& mesh, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { concurrency::parallel_for(size_t(0), mesh.Indices.size(), size_t(3), [=](size_t i){ Vertex v1 = mesh.Vertices[mesh.Indices[i]]; Vertex v2 = mesh.Vertices[mesh.Indices[i + 1]]; Vertex v3 = mesh.Vertices[mesh.Indices[i + 2]]; Point p1 = Project(v1, worldMatrix, viewMatrix, projectMatrix); Point p2 = Project(v2, worldMatrix, viewMatrix, projectMatrix); Point p3 = Project(v3, worldMatrix, viewMatrix, projectMatrix); DrawTriangle(p1, p2, p3, mesh.texture.get()); }); /*for (size_t i = 0; i < mesh.Indices.size(); i += 3) { Vertex v1 = mesh.Vertices[mesh.Indices[i]]; Vertex v2 = mesh.Vertices[mesh.Indices[i + 1]]; Vertex v3 = mesh.Vertices[mesh.Indices[i + 2]]; Point p1 = Project(v1, worldMatrix, viewMatrix, projectMatrix); Point p2 = Project(v2, worldMatrix, viewMatrix, projectMatrix); Point p3 = Project(v3, worldMatrix, viewMatrix, projectMatrix); DrawTriangle(p1, p2, p3, mesh.texture.get()); }*/ } void XM_CALLCONV Rasterizer::RenderX(const Mesh& mesh, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { for (int i = 24; i < 30; i += 3) { Vertex v1 = mesh.Vertices[mesh.Indices[i]]; Vertex v2 = mesh.Vertices[mesh.Indices[i + 1]]; Vertex v3 = mesh.Vertices[mesh.Indices[i + 2]]; Point p1 = Project(v1, worldMatrix, viewMatrix, projectMatrix); Point p2 = Project(v2, worldMatrix, viewMatrix, projectMatrix); Point p3 = Project(v3, worldMatrix, viewMatrix, projectMatrix); DrawTriangle(p1, p2, p3, mesh.texture.get()); } } void XM_CALLCONV Rasterizer::RenderZ(const Mesh& mesh, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { for (int i = 0; i < 6; i += 3) { Vertex v1 = mesh.Vertices[mesh.Indices[i]]; Vertex v2 = mesh.Vertices[mesh.Indices[i + 1]]; Vertex v3 = mesh.Vertices[mesh.Indices[i + 2]]; Point p1 = Project(v1, worldMatrix, viewMatrix, projectMatrix); Point p2 = Project(v2, worldMatrix, viewMatrix, projectMatrix); Point p3 = Project(v3, worldMatrix, viewMatrix, projectMatrix); DrawTriangle(p1, p2, p3, mesh.texture.get()); } } void XM_CALLCONV Rasterizer::RenderY(const Mesh& mesh, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { for (int i = 12; i < 18; i += 3) { Vertex v1 = mesh.Vertices[mesh.Indices[i]]; Vertex v2 = mesh.Vertices[mesh.Indices[i + 1]]; Vertex v3 = mesh.Vertices[mesh.Indices[i + 2]]; Point p1 = Project(v1, worldMatrix, viewMatrix, projectMatrix); Point p2 = Project(v2, worldMatrix, viewMatrix, projectMatrix); Point p3 = Project(v3, worldMatrix, viewMatrix, projectMatrix); DrawTriangle(p1, p2, p3, mesh.texture.get()); } } void XM_CALLCONV Rasterizer::RenderCMOModel(CMOModel* model, DirectX::FXMMATRIX worldMatrix, DirectX::FXMMATRIX viewMatrix, DirectX::FXMMATRIX projectMatrix) { for (auto mesh : model->meshes) { RenderMeth(*mesh, worldMatrix, viewMatrix, projectMatrix); } }