注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
前两周完成了Amazon OA2,coding 部分抽到的水题,直接分配群面了(也可能是WS没做好)。分享一下 准备OA期间,自己写的 热门OA C++代码(在C98下 编译测试过)
文档第一部分代码,在MST之前的代码是 oder dependency
#include <stdio.h> #include<iostream> //* for string, vector, and so on #include<string> //* for string #include<queue>//* priority_queue #include<algorithm>// sort #include<functional>//* greater #include<vector> #include<map>
using namespace std;
//* order dependency
struct gnode{ int id, degree; vector<int> adj_ids; };
vector<gnode> make_graph(vector<pair<int, int> >& preq, int ncs){ vector<gnode> nodes; for(int i = 0; i< ncs; i++){ gnode nd; nd.id = i; nd.degree = 0; nodes.push_back(nd); } for(int i =0; i< preq.size(); i++){ int cid = preq[i].second; int adj = preq[i].first; nodes[adj].degree++; //* note! nodes[cid].adj_ids.push_back(adj); } return nodes; }
void helper(vector<int>& ret, int ncs, vector<gnode>& nodes ){ if(ret.size() == ncs) return; int judge = 0; for(int i = 0; i < nodes.size(); i++){ gnode& nd = nodes[i]; if(nd.degree == 0){ judge = 1; ret.push_back(nd.id); nd.degree = -1; for(int j = 0; j < nd.adj_ids.size(); j++) nodes[nd.adj_ids[j]].degree--; } } if(not judge) return; helper(ret, ncs, nodes); } vector<int> findOrder(int numCourses, vector<pair<int, int> >& prerequisites) { vector<int> ret, empty; vector<gnode> nodes = make_graph(prerequisites, numCourses); helper(ret, numCourses, nodes); if(ret.size() != numCourses) return empty; return ret; }
//* MST class MST{ public: struct connection{ string node1, node2; int cost; }; struct node{ string city; map<string, int> adj_cost; }; void make_graph(map<string,node>&graph, vector<connection>::iterator conit, vector<connection>::iterator endit){ if(conit == endit) return; string city1 = conit->node1, city2 = conit->node2; int cost = conit->cost; graph[city1].city = city1; graph[city1].adj_cost[city2] = cost; graph[city2].city = city2; graph[city2].adj_cost[city1] = cost; //* important: to include two city, oherwise graph.size() will no eft"> struct RandomListNode { int label; RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) {} }; RandomListNode *copyRandomList(RandomListNode *head) { if(not head) return NULL; map<RandomListNode*, RandomListNode*> hash; //* the first is to record the orig, the second is the p2 new node RandomListNode* p1 = head; RandomListNode* p2 = new RandomListNode(p1->label); hash[head] = p2;//* can be also used for return; while(p1){ if(p1->next){ if(hash[p1->next]) p2->next = hash[p1->next]; //* note not p1->next, because this was just created new node else{ p2->next = new RandomListNode(p1->next->label); hash[p1->next] = p2->next; } } if(p1->random){ if(hash[p1->random]) p2->random = hash[p1->random]; else{ p2->random = new RandomListNode(p1->random->label); hash[p1->random] = p2->random; } } p1 = p1->next; p2 = p2->next; } return hash[head]; } };
|