コード例 #1
0
int main() {
  
  std::cout << "start" << std::endl;
  typedef DiGraphAdjMatrix<std::string, int> Graph;
  Graph g;
  Graph::VertexPtr s = g.AddVertex("s");
  Graph::VertexPtr v1 = g.AddVertex("v1");
  Graph::VertexPtr v2 = g.AddVertex("v2");
  Graph::VertexPtr v3 = g.AddVertex("v3");
  Graph::VertexPtr v4 = g.AddVertex("v4");
  Graph::VertexPtr v5 = g.AddVertex("v5");
  Graph::VertexPtr v6 = g.AddVertex("v6");
  Graph::VertexPtr v7 = g.AddVertex("v7");
  g.AddEdge(*s, *v1, 1);
  g.AddEdge(*s, *v2, 1);
  g.AddEdge(*s, *v3, 1);
  g.AddEdge(*v1, *v4, 1);
  g.AddEdge(*v1, *v5, 1);
  g.AddEdge(*v5, *v6, 1);
  g.AddEdge(*v6, *v7, 1);

  DepthFirstVertexIterator<std::string, int> dfi(g, *s);
  while (dfi.HasNext()) {
    std::cout << "v:" << dfi.Next()->GetValue() << std::endl;
  }
  
  return 0;
}
コード例 #2
0
        Graph GeneratorWHEEL::DoGenerate(list<int> parameter)
        {
            int n = parameter.front();
            Graph result;

            Vertex* center = *(result.AddVertex());
            Coordinates centercoords(2, 0.0f);
            center->SetCoordinates(centercoords);

            Vertex* prev = NULL;
            Vertex* first = NULL;
            for(int i = 0; i < n; i++)
            {
                Vertex* v = *(result.AddVertex());

                Coordinates coords(2);
                coords[0] = -5 * cos(i * (2 * M_PI / n) + M_PI/2);
                coords[1] =  5 * sin(i * (2 * M_PI / n) + M_PI/2);
                v->SetCoordinates(coords);

                if(prev != NULL)
                    result.AddEdge(prev, v);
                else
                    first = v;

                result.AddEdge(v, center);
                prev = v;
            }

            if(prev != NULL && first != NULL)
                result.AddEdge(prev, first);

            return result;
        }
コード例 #3
0
ファイル: 3114.cpp プロジェクト: AOQNRMGYXLMV/mycode
int main()
{
	while(scanf("%d%d", &n, &m) == 2 && n) {
		g.init();
		while(m--) {
			int u, v, w; scanf("%d%d%d", &u, &v, &w);
			g.AddEdge(u, v, w);
		}

		find_scc();

		t.init();
		for(int u = 1; u <= n; u++) {
			for(int i = g.head[u]; ~i; i = g.edges[i].nxt) {
				int v = g.edges[i].v;
				if(sccno[u] == sccno[v]) continue;
				int w = g.edges[i].w;
				t.AddEdge(sccno[u], sccno[v], w);
			}
		}

		int q; scanf("%d", &q);
		while(q--) {
			int u, v; scanf("%d%d", &u, &v);
			int ans = SPFA(sccno[u], sccno[v]);
			if(ans < INF) printf("%d\n", ans);
			else printf("Nao e possivel entregar a carta\n");
		}
		printf("\n");
	}

	return 0;
}
コード例 #4
0
ファイル: Graph_part2.cpp プロジェクト: vjain05/CSE100labs
int main() {
    Graph G;
	string input;
	int opcode;
	string ver1;
	string ver2;
	int weigh;
	cin>>input;
	while(input!="END"){
		G.vertices.push_back(input);
		cin>>input;
	}
	cin>>input;
	while(input!="END"){
		ver1=input;
		cin>>input;
		ver2=input;
		cin>>weigh;
		if(G.FindVertex(ver1)==1 && G.FindVertex(ver2)==1){
			G.AddEdge(ver1,ver2,weigh);
		}
		cin>>input;
	}
	//G.PrintOut();
	cin>>opcode;
	while(opcode!=0){
		if(opcode==1){
			cin>>ver1;
			cout<<G.FindVertex(ver1)<<endl;
		}
		else{
コード例 #5
0
int main()
{
	int n,m,i,x,y,j;
	Graph gr;
	n=inp();m=inp();
	gr.init(n,m);
	vector<pair<int, int> > v;
	for(i=0;i<m;i++)
	{
        x=inp();y=inp();
        if(x!=y) v.push_back(make_pair(x-1,y-1));
	}
	sort(v.begin(),v.end());
	for(i=0;i<v.size();)
	{
        gr.AddEdge(v[i].first, v[i].second, 0);
        gr.AddEdge(v[i].second, v[i].first, 1);
        j=i;i++;
        while(i<v.size() && v[i].first==v[j].first && v[i].second==v[j].second) i++;
	}
	//gr.printgr();
	x = gr.dijkstra(0,n-1);
	if(x==INT_MAX) printf("-1\n");
    else printf("%d\n",x);
	return 0;
}
コード例 #6
0
ファイル: UVa_10048.cpp プロジェクト: RaWinDing/ACM
int main() {
    int tot_case = 0;
    while (scanf("%d%d%d", &c, &s, &q) && (c || s || q)) {
        // Input.
        graph.Init(c);
        for (int i = 0; i < s; i++) {
            int c1, c2, d;
            scanf("%d%d%d", &c1, &c2, &d);
            c1--, c2--;
            graph.AddEdge(c1, c2, d);
            graph.AddEdge(c2, c1, d);
        }
        // Solve.
        Floyd::Go(graph.mat, c);
        // Output.
        printf("%s", tot_case ? "\n" : "");
        printf("Case #%d\n", ++tot_case);
        for (int i = 0; i < q; i++) {
            int c1, c2, d;
            scanf("%d%d", &c1, &c2);
            c1--, c2--;
            if (graph.mat[c1][c2] != INF) {
                printf("%d\n", graph.mat[c1][c2]);
            } else {
                printf("no path\n");
            }
        }
    }
    return 0;
}
コード例 #7
0
ファイル: main.cpp プロジェクト: juanplopes/old-uerj-projects
int main() {
    int n, m, a, b, c;
    n = m = a = b = c = 0;
    double inicio , fim;
    string arquivo;

    cout << "Digite o nome do arquivo com os dados do grafo." << endl;
    cin >> arquivo;
    
    ifstream fin(arquivo.c_str() , ios::binary);
    
    fin >> n >> m;
    Graph* graph = new Graph(n);
        
    for(int i=0; i<m; i++) {
        fin >> a >> b >> c;
        graph->AddEdge(a, b, c);
    }
    cout << "Todos os vertices foram adicionados" << endl;
    cout << " n=" << n << ", m=" << m << endl << endl;        

    while(true) {
        cout << "Digite s (saida) e t (destino). 0 0 para sair" << endl;
        cin >> a >> b; if (!a && !b) break;
        miolo(false, graph, a, b);
        miolo(true, graph, a, b);
    }
        
    delete(graph);
}
コード例 #8
0
ファイル: 1067.cpp プロジェクト: vadimkantorov/acm
void main()
{
	//freopen("input.txt","r",stdin);
	g.AddRoot();
	int n;
	cin >> n;
	cin.get();
	string tmp,name;
	for(int i = 0;i < n; i++)
	{
		cin >> tmp;
		tmp += '\\';
		int prev = 0;
		for(int j = 0; j < tmp.length(); j++)
		{
			if(tmp[j] != '\\')
				name += tmp[j];
			else
			{
				prev = g.AddEdge(prev,name);
				name = "";
			}
		}
	}

	for(int i = 0; i < g.V(); i++)
		g.M[i].Sort();
	print(0,-1);
}
コード例 #9
0
ファイル: UVaOJ_567.cpp プロジェクト: RaWinDing/ACM
void Read(int x, int num) {
    for (int i = 0; i < num; i++) {
        int y;
        scanf("%d", &y);
        graph.AddEdge(x, y - 1, 1);
        graph.AddEdge(y - 1, x, 1);
    }
}
コード例 #10
0
int main()
{
    int t, tc, n, m, i, j, k, u, v, c;
    scanf("%d", &tc);
    for(t = 1; t <= tc; t++)
    {
    	scanf("%d%d", &n, &m);
    	Graph gr; gr.init(n,m);
    	for(i = 0; i <m; i++)
    	{
    		scanf("%d%d%d", &u, &v, &c);
    		if(u > v)
    		{
    			int tem = u;
    			u = v;
    			v = tem;
    		}
    		arr[i].u = u;
    		arr[i].v = v;
    		arr[i].ind = i;
    		arr[i].imp = 0;
    		gr.AddEdge(u, v, c, i);
    	}
    	for(i = 0; i < n; i++)
    		gr.dijkstra(i);
        printf("Case #%d: \n", t);
        sort(arr, arr + m, cmp);
        for(i = 0; i < m;i++)
        {
        	//printf("ed %d = %d u = %d v = %d \n", i, arr[i].imp, arr[i].u, arr[i].v);
        	if(arr[i].imp == 1)
        	{
        		while((i + 1 < m) && (arr[i].u == arr[i+1].u) && (arr[i].v == arr[i+1].v))
        		{
        			arr[i+1].imp = 1;
        			i++;
        		}
        	}
        }
        for(i = m-1; i >= 0;i--)
        {
        	//printf("ed %d = %d u = %d v = %d \n", i, arr[i].imp, arr[i].u, arr[i].v);
        	if(arr[i].imp == 1)
        	{
        		while((i -1 >= 0) && (arr[i].u == arr[i-1].u) && (arr[i].v == arr[i-1].v))
        		{
        			arr[i-1].imp = 1;
        			i--;
        		}
        	}
        	else
        	{
        		printf("%d\n", arr[i].ind);
        	}
        }
    }
    return 0;
}
コード例 #11
0
ファイル: quadapult.cpp プロジェクト: hyperlogic/quadapult
Graph* BuildGraph(Sprite* root)
{
	Graph* graph = new Graph(root);

	SortAndSweep::OverlapPairSet::const_iterator setIter = s_sortAndSweep.GetOverlapPairSet().begin();
	SortAndSweep::OverlapPairSet::const_iterator setEnd = s_sortAndSweep.GetOverlapPairSet().end();
	for (; setIter != setEnd; ++setIter)
	{
		const Sprite* a = reinterpret_cast<const Sprite*>(setIter->first->userPtr);
		const Sprite* b = reinterpret_cast<const Sprite*>(setIter->second->userPtr);
		assert(a && b);

		if (a->GetDepth() < b->GetDepth())
			graph->AddEdge(a, b);
		else
			graph->AddEdge(b, a);
	}

	return graph;
}
コード例 #12
0
ファイル: Graph.cpp プロジェクト: bozzkar/visiting-graphs
Graph* CloneGraph(Graph* origGraph){
	cout <<endl<< "Cloning graph" << endl;
	//cout << "-------------" << endl;

	Node* root = origGraph->GetRoot();
	Graph* clonedGraph = new Graph();
	if (root == NULL)
		return NULL;
	queue<Node*> q;
	unordered_map<Node*, Node*> mapping;
	Node* friendNode;

	Node* clonedRoot = clonedGraph->AddNode(root->GetLabel());
	//cout << "Cloned new Nodes:" << clonedRoot->GetLabel() << ",";
	mapping[root] = clonedRoot;
	q.push(root);

	while (!q.empty()){
		Node* current = q.front();
		q.pop();

		for (int i = 0; i < current->GetFriends().size(); i++){
			friendNode = current->GetFriend(i);
			if (mapping[friendNode]){
				clonedGraph->AddEdge(mapping[current], mapping[friendNode]);
			}
			else{
				Node* newNode = clonedGraph->AddNode(friendNode->GetLabel());
				//cout << newNode->GetLabel()<<",";
				mapping[friendNode] = newNode;
				clonedGraph->AddEdge(mapping[current], newNode);
				q.push(friendNode);
			}

		}
	}
	return clonedGraph;
}
コード例 #13
0
ファイル: 1272.cpp プロジェクト: vadimkantorov/acm
void main()
{
	//freopen("input.txt","r",stdin);

	int n,k;
	scanf("%d%d%d",&n,&k);
	for(int i = 0; i < k; i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		g.AddEdge(u,v);
	}
	printf("%d",g.GetConnectedComponentsCount(n) - 1);
}
コード例 #14
0
int main() {
	Graph g;
	int v1 = g.AddVertice();
	int v2 = g.AddVertice();
	int v3 = g.AddVertice();
	int v4 = g.AddVertice();
	int v5 = g.AddVertice();

	g.AddEdge(v1, v2);
	g.AddEdge(v1, v3);
	g.AddEdge(v1, v4);
	g.AddEdge(v1, v5);

	g.AddEdge(v2, v1);
	g.AddEdge(v2, v3);

	g.AddEdge(v1, v1);

	g.bfs(v5);

	g.print();

	return 0;
}
コード例 #15
0
ファイル: graph.cpp プロジェクト: ingver/dsa-labs
//---------------------------------------------------------------------------
int  Graph::Hamiltonian(int v, int w, int Length, bool * Labelled, Graph & G)
{
	if (v == w)
		return Length == 0 ? 1 : 0;
	Labelled[v] = true;
	for (int t = 0; t < _Size; t++)
		if( _m[v][t] < MAXDOUBLE && _m[v][t] != 0 && !Labelled[t])
			if ( Hamiltonian(t, w, Length - 1, Labelled, G))
			{
				G.AddEdge(t,v,_m[t][v]);
				G.AddEdge(v,t,_m[v][t]);
				return 1;
			}
			Labelled[v] = false;
		return 0;
}
コード例 #16
0
int main() {

    Graph G;
    string input;
    cin >> input;
    while(input != "END") {
        G.vertices.push_back(input);
        cin >> input;
    }
    string first, second;
    cin >> first;
    int weight;
    while(first != "END") {
        cin >> second;
        cin >> weight;
        G.AddEdge(first,second,weight);
        cin >> first;
    }
    //G.PrintOut();
    int opcode;
    cin >> opcode;
    string A, B;
    while(opcode != 0) {
        switch(opcode)
        {
        case 1:
            cin >> A;
            if(G.FindVertex(A))
                cout << 1 << endl;
            else
                cout << 0 << endl;
        break;
        case 2:
            cin >> A;
            cin >> B;
            cout << G.FindEdgeCost(A, B) << endl;
            break;
        case 3:
            cin >> A;
            cin >> B;
            cout << G.IsReachable(A, B) << endl;
            break;
        }
        cin >> opcode;
    }
}
コード例 #17
0
    Graph* BuildQueryGraph(const Graph* gQuery, const Subgraph& subg)
    {
        typedef typename Graph::VertexProp VertexProp;
        typedef typename Graph::EdgeType Edge;
        typedef typename Graph::DirectedEdgeType DirectedEdge;
        int num_vertices = subg.VertexCount();
        std::map<uint64_t, uint64_t> norm_id_map;

        Graph* g = new Graph(num_vertices);
   
        for (Subgraph::VertexIterator it = subg.BeginVertexSet();
                it != subg.EndVertexSet(); it++) {
            uint64_t u = *it;
            std::map<uint64_t, uint64_t>::iterator id_map_it = norm_id_map.find(u);
            if (id_map_it == norm_id_map.end()) {
                uint64_t mapped_u = norm_id_map.size();
                norm_id_map[u] = mapped_u;
                const VertexProp& u_prop = 
                        gQuery->GetVertexProperty(u);
                g->AddVertex(mapped_u, u_prop);
            }
        }

        g->AllocateAdjacencyLists();
 
        for (Subgraph::EdgeIterator it = subg.BeginEdgeSet(); 
                it != subg.EndEdgeSet(); it++) {
            const dir_edge_t& dir_e = *it;
            DirectedEdge dir_edge;
            dir_edge.s = norm_id_map[dir_e.s];
            dir_edge.t = norm_id_map[dir_e.t];
            int num_edges;
            const Edge* edges = gQuery->Neighbors(dir_e.s, num_edges);
            for (int i = 0; i < num_edges; i++) {
                if (edges[i].dst == dir_e.t) {
                    dir_edge.type = edges[i].type;
                    dir_edge.edge_data = edges[i].edge_data;
                    break;
                }
            }
            g->AddEdge(dir_edge);
        }

        return g;
    }
コード例 #18
0
ファイル: UVa_10099.cpp プロジェクト: WinDaLex/Programming
int main() {
    int tot_case = 0;
    while (scanf("%d%d", &n, &r) && (n || r)) {
        // Input.
        graph.Init(n);
        for (int i = 0; i < r; i++) {
            scanf("%d%d%d", &c1, &c2, &p);
            graph.AddEdge(c1 - 1, c2 - 1, p);
            graph.AddEdge(c2 - 1, c1 - 1, p);
        }
        scanf("%d%d%d", &s, &d, &t);
        // Solve.
        Dijkstra::Go(dis, graph.mat, n, s - 1);
        // Output.
        printf("Scenario #%d\n", ++tot_case);
        printf("Minimum Number of Trips = %d\n", (t + dis[d - 1] - 2) / (dis[d - 1] - 1));
        printf("\n");
    }
    return 0;
}
コード例 #19
0
int main () {
	Graph myGraph;
	Vertex * root;
	cout << "Simply enter the input and press Ctrl + Z to send EOF command" << endl;
	for (string line; getline(std::cin, line);) {
        size_t found;
        if ((found = line.find(" ")) != string::npos) {
        	if (root != NULL) {
        		root = myGraph.AddVertex(line.substr(0,found));
        		myGraph.AddVertex(line.substr(found + 1, string::npos));
        	}
        	else {
        		myGraph.AddVertex(line.substr(0,found));
        		myGraph.AddVertex(line.substr(found + 1, string::npos));
        	}
        	myGraph.AddEdge(line.substr(0,found), line.substr(found + 1, string::npos));
        }
    }
    myGraph.PrintSolution();
	return 0;
}
// Алгоритм Джонсона с использованием алгоритма Дейкстры на самоорганизующейся куче
void Djonson_SelfOrganizationHeap(int** dist, Graph ADJ, int num_vert)
{
    Graph AdditionalGraph = ADJ;

    AdditionalGraph.AddVertex(ADJ.GetNumOfVertex() + 1);

    int* dist_Bellman_Ford = new int[AdditionalGraph.GetNumOfVertex()];// Он будет содержать значения не больше нуля

    for(int i = 0; i < AdditionalGraph.GetNumOfVertex() - 1; i++)
        AdditionalGraph.AddEdge(AdditionalGraph.GetNumOfVertex() - 1, i, 0);

    // Применяем Беллмана-Форда для графа с наличием отрицательных весов ребер
    if(Bellman_Ford(dist_Bellman_Ford, AdditionalGraph, AdditionalGraph.GetNumOfVertex(), AdditionalGraph.GetNumOfVertex() - 1))
    {
        for(ADJ.Reset(); !ADJ.IsEnd(); ADJ.GoNext())// Делаем неотрицательные веса для алгоритма Дейкстры
        {
            ADJ.SetWeightOfEdge(ADJ.GetCurrVertex(),
                ADJ.GetCurrEdge().vertB,
                ADJ.GetCurrEdge().weight + dist_Bellman_Ford[ADJ.GetCurrVertex()] - dist_Bellman_Ford[ADJ.GetCurrEdge().vertB]);
        }

        for(int i = 0; i < ADJ.GetNumOfVertex(); i++)
        {
            Dijkstra_SelfOrganizationHeap(dist[i], ADJ, ADJ.GetNumOfVertex(), i);
            for(int j = 0; j < ADJ.GetNumOfVertex(); j++)
                dist[i][j] = dist[i][j] + dist_Bellman_Ford[j] - dist_Bellman_Ford[i];
        }

        for(ADJ.Reset(); !ADJ.IsEnd(); ADJ.GoNext())// Обратно меняем веса на предыдущие у графа ADJ
        {
            ADJ.SetWeightOfEdge(ADJ.GetCurrVertex(),
                ADJ.GetCurrEdge().vertB,
                ADJ.GetCurrEdge().weight + dist_Bellman_Ford[ADJ.GetCurrEdge().vertB ] - dist_Bellman_Ford[ADJ.GetCurrVertex()]);
        }
    }
    else
        cout << "Graph contains a cycle of negative weight" << endl;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: crybot/Algorithms
int main()
{
    int vertex;
    string str;
    Graph InitialGraph;
    pair<int, int> tuple;
    vector<string> tokens;
    StopWatch watch;

    ifstream ff("dijkstraData.txt");

    while(ff.good())
    {
        getline(ff, str);
        tokens = Tokenize(str);
        vertex = atoi(tokens[0].c_str());
        for (unsigned i = 1; i<tokens.size(); i++)
        {
            tuple = Split(tokens[i]);
            InitialGraph.AddEdge(Edge(vertex, tuple.first), tuple.second);
        }
    }
    ff.close();

    watch.Start();

    InitialGraph.ShortestPath(1);

    watch.Stop();

    cout << "Tempo impiegato: " << watch.ElapsedMilliseconds() << endl;

//    clock_t end = clock();
//    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
//    cout << "Tempo impiegato: " << elapsed_secs << endl;

    return 0;
}
コード例 #22
0
ファイル: 1471.cpp プロジェクト: vadimkantorov/acm
void main()
{
	//freopen("input.txt","r",stdin);
	
	int n;
	scanf("%d",&n);
	for(int i = 0; i < n-1; i++)
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		g.AddEdge(u,v,w);
	}
	g.PreProcess();
	
	int m;
	scanf("%d",&m);
	for(int i = 0; i < m; i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		printf("%d\n",g.Path(u,v));
	}
}
コード例 #23
0
ファイル: bfs1.cpp プロジェクト: vadimkantorov/urfu
int main()
{
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);

	int n;
	scanf("%d",&n);

	for(int i = 1; i <= n; i++)
	{
		while(true)
		{
			int v;
			scanf("%d", &v);
			if(v == 0)
				break;
			g.AddEdge(i,v);
		}
	}

	vector<vector<int>> res = g.DivideIntoTwoParts(n);
	if(res.empty())
		puts("N");
	else
	{
		puts("Y");
		for(int k = 0; k < 2; k++)
		{
			for(int i = 0; i < res[k].size(); i++)
				printf("%d ",res[k][i]);
			if(k == 0)
				puts("0");
		}
	}
	
	return 0;
}
コード例 #24
0
ファイル: 1210.cpp プロジェクト: vadimkantorov/acm
void main()
{
	//freopen("input.txt","r",stdin);
	
	int levels;
	scanf("%d",&levels);

	int lastIDs[30], newIDs[30];
	lastIDs[0] = 0;
	int planets = 0, maxt;
	for(int i = 0; i < levels; i++)
	{
		int curPls;
		scanf("%d",&curPls);
		if(i == levels-1)
			maxt = curPls;
		for(int j = 0; j < curPls; j++)
		{
			newIDs[j] = ++planets;
			Edge e;
			while(true)
			{
				int parent;
				scanf("%d",&parent);
				if(parent == 0) break;
				
				e.Vertex = newIDs[j];
				scanf("%d",&e.Weight);
				g.AddEdge(lastIDs[parent-1],e);
			}
		}
		for(int j = 0; j < 30; j++)
			lastIDs[j] = newIDs[j];
		scanf("\n*\n");
	}
	printf("%d",g.DagShortestPaths(planets+1,0,maxt));
}
コード例 #25
0
ファイル: main.cpp プロジェクト: kielfriedt/Data-Structures
int main()
{
	Graph g;
	char tempname[256];
	char * sendclass;
	char * preclass;
	bool quit = false;
	int answer = 0;
	welcome();
	while(quit != true)
	{
		cout << "1) Adding class\n"
		<< "2) Adding prerequisite class\n"
		<< "3) Removing class\n"
		<< "4) Removing prerequisite class\n"
		<< "5) Display Graph\n"
		<< "6) Quit\n";
		cin >> answer;
		cin.ignore();
		switch(answer)
		{
			case 1:
				cout << "What is the class?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				sendclass = new char[strlen(tempname) + 1];
				strcpy(sendclass,tempname);
				if(g.AddVert(sendclass) == 1)
					cout << "You have successfully added that class\n";
				else
					cout << "We were unable to add that class\n";
				break;
			case 2:
				cout << "What is the prerequisite class?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				preclass = new char[strlen(tempname) + 1];
				strcpy(preclass,tempname);
				cout << "What is the class?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				sendclass = new char[strlen(tempname) + 1];
				strcpy(sendclass,tempname);
				if(g.AddEdge(sendclass,preclass) == 1)
					cout << "You have successfully added that prerequisite class\n";
				else
					cout << "We were unable to add that prerequisite class\n";
				break;
			case 3:
				cout << "What class you would like to remove?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				sendclass = new char[strlen(tempname) + 1];
				strcpy(sendclass,tempname);
				if(g.RemoveVert(sendclass) == 1)
					cout << "You have successfully removed that class\n";
				else
					cout << "We were unable to remove that class\n";
				break;
			case 4:
				cout << "What prerequisite class you would like to remove?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				preclass = new char[strlen(tempname) + 1];
				strcpy(preclass,tempname);
				cout << "What is the class?\n";
				cin.get(tempname,256,'\n');
				cin.ignore();
				sendclass = new char[strlen(tempname) + 1];
				strcpy(sendclass,tempname);
				if(g.RemoveEdge(sendclass,preclass) == 1)
					cout << "You have successfully removed that prerequisite class\n";
				else
					cout << "We were unable to remove that prerequisite class\n";
				break;
			case 5:
				g.Display();
				break;
			case 6:
				quit = true;
				break;
			default:
				cout << "please enter in a valid option\n";
				break;
		}
	}
	signoff();
	return 0;
}
コード例 #26
0
ファイル: Inconsistency.cpp プロジェクト: DavidMChan/hog2
Graph *BuildInconsistentGraph(int d, int w, int h, int c1, int c2)
{
	//int d = 2;
	gFrom = d*w*h-1;
	gTo = 0;
	
	Graph *g = new Graph();
	int cost[d][w][h];
	int index[d][w][h];
	for (int z = 0; z < d; z++)
	{
		for (int x = 0; x < w; x++)
		{
			for (int y = 0; y < h; y++)
			{
				node *n;
				cost[z][x][y] = MAXINT;
				index[z][x][y] = g->AddNode(n = new node(""));
				n->SetLabelF(GraphSearchConstants::kXCoordinate, -1.0+2.0*(double)x/(double)(w-1.0));
				n->SetLabelF(GraphSearchConstants::kYCoordinate, -1.0+2.0*(double)y/(double)(h-1.0));
				if (d > 1)
					n->SetLabelF(GraphSearchConstants::kZCoordinate, -1.0+2.0*(double)z/(double)(d-1.0));
				else
					n->SetLabelF(GraphSearchConstants::kZCoordinate, 0);
			}
		}
	}
	for (int z = 0; z < d; z++)
	{
		for (int x = 0; x < w; x++)
		{
			for (int y = 0; y < h; y++)
			{
				if ((x == 0) && (y == 0) && (z == 0))
				{
					if (d > 1)
						g->AddEdge(new edge(index[z+1][x][y], index[z][x][y], c2));
					if (w > 1)
						g->AddEdge(new edge(index[z][x+1][y], index[z][x][y], c2));
					g->AddEdge(new edge(index[z][x][y+1], index[z][x][y], c2));
					continue;
				}
				if (z+1 <d)
					g->AddEdge(new edge(index[z+1][x][y], index[z][x][y], 1+random()%c1));
				if (x+1 <w)
					g->AddEdge(new edge(index[z][x+1][y], index[z][x][y], 1+random()%c1));
				if (y+1 < h)
					g->AddEdge(new edge(index[z][x][y+1], index[z][x][y], 1+random()%c1));
			}
		}
	}
	cost[0][0][0] = 0;
	while (1)
	{
		int changes = 0;

		for (int z = 0; z < d; z++)
		{
			for (int x = 0; x < w; x++)
			{
				for (int y = 0; y < h; y++)
				{
					if (z+1 <d)
					{
						int from1 = index[z][x][y];
						int to1 = index[z+1][x][y];
						edge *e = g->FindEdge(from1, to1);
						if (cost[z+1][x][y] > cost[z][x][y] + e->GetWeight())
						{
							cost[z+1][x][y] = cost[z][x][y] + g->FindEdge(index[z][x][y], index[z+1][x][y])->GetWeight();
							changes++;
						}
					}
					if (x+1 <w)
					{
						if (cost[z][x+1][y] > cost[z][x][y] + g->FindEdge(index[z][x][y], index[z][x+1][y])->GetWeight())
						{
							cost[z][x+1][y] = cost[z][x][y] + g->FindEdge(index[z][x][y], index[z][x+1][y])->GetWeight();
							changes++;
						}
					}
					if (y+1 < h)
					{
						if (cost[z][x][y+1] > cost[z][x][y] + g->FindEdge(index[z][x][y], index[z][x][y+1])->GetWeight())
						{
							cost[z][x][y+1] = cost[z][x][y] + g->FindEdge(index[z][x][y], index[z][x][y+1])->GetWeight();
							changes++;
						}
					}
				}
			}
		}

		if (changes == 0)
			break;
	}
	
	for (int z = 0; z < d; z++)
	{
		for (int x = 0; x < w; x++)
		{
			for (int y = 0; y < h; y++)
			{
				//printf("cost of node %d (%d, %d) is %d\n", x, y, index[x][y], cost[x][y]);
				node *n = g->GetNode(index[z][x][y]);
				if (cost[z][x][y] == 0)
					n->SetLabelF(GraphSearchConstants::kHCost, 0);
				else {
					//int val = ((random()%4) == 0)?(random()%(cost[z][x][y]+1)):0;
					int val = random()%(cost[z][x][y]+1);
					//printf("Assigning h = %d\n", val);
					n->SetLabelF(GraphSearchConstants::kHCost, (double)val);
				}
			}
		}
	}
	return g;
}
コード例 #27
0
        Graph ImportFilterGML::Import(std::istream& is)
        {
            OpenGraphtheory::Import::GMLLexer l(is);
            GMLTreeNode* GMLTreeRoot = new GMLTreeNode;
            l.yylex(GMLTreeRoot);

            Graph result;
            map<int, Vertex*> VertexRegister;
            GMLValueNode* GraphNode = GetValue<GMLValueNode>(GMLTreeRoot, "GRAPH");
            if(GraphNode == NULL)
                throw "GML Document contains no top-level element \"graph\" with children";

            bool GraphDirected = false;
            GMLValueInt* directed = GetValue<GMLValueInt>(GraphNode->value, "DIRECTED");
            if(directed != NULL)
                GraphDirected = directed->value == 1;

            // Iterate Nodes
            for(list<pair<string, GMLValue*> >::iterator n = GraphNode->value->Children.begin(); n != GraphNode->value->Children.end(); n++)
            {
                string N = n->first;
                transform(N.begin(), N.end(), N.begin(), ::toupper);
                if(N != "NODE")
                    continue;
                GMLValueNode *NValue = dynamic_cast<GMLValueNode*>(n->second);
                if(NValue == NULL)
                    continue;

                GMLValueInt* id = GetValue<GMLValueInt>(NValue->value, "ID");
                if(id == NULL)
                    continue;
                if(VertexRegister.find(id->value) != VertexRegister.end())
                    throw "Multiple nodes with the same id";
                Vertex* v = *(result.AddVertex());
                VertexRegister[id->value] = v;

                GMLValueString* label = GetValue<GMLValueString>(NValue->value, "LABEL");
                if(label != NULL)
                    v->SetLabel(label->value);

                GMLValueNode* graphics = GetValue<GMLValueNode>(NValue->value, "GRAPHICS");
                if(graphics != NULL)
                {
                    vector<float> coordinates;

                    GMLValueFloat* xf = GetValue<GMLValueFloat>(graphics->value, "X");
                    GMLValueInt* xi = GetValue<GMLValueInt>(graphics->value, "X");
                    if(xf != NULL) coordinates.push_back(xf->value);
                    else if(xi != NULL) coordinates.push_back(xi->value);
                    else coordinates.push_back(0);

                    GMLValueFloat* yf = GetValue<GMLValueFloat>(graphics->value, "Y");
                    GMLValueInt* yi = GetValue<GMLValueInt>(graphics->value, "Y");
                    if(yf != NULL) coordinates.push_back(yf->value);
                    else if(yi != NULL) coordinates.push_back(yi->value);
                    else coordinates.push_back(0);

                    GMLValueFloat* zf = GetValue<GMLValueFloat>(graphics->value, "Z");
                    GMLValueInt* zi = GetValue<GMLValueInt>(graphics->value, "Z");
                    if(zf != NULL) coordinates.push_back(zf->value);
                    else if(zi != NULL) coordinates.push_back(zi->value);
                    // a third coordinate is not enforced

                    v->SetCoordinates(coordinates);

                    GMLValueFloat* wf = GetValue<GMLValueFloat>(graphics->value, "W");
                    GMLValueInt* wi = GetValue<GMLValueInt>(graphics->value, "W");
                    if(wf != NULL) v->SetWeight(wf->value);
                    else if(wi != NULL) v->SetWeight(wi->value);

                }

            }

            for(list<pair<string, GMLValue*> >::iterator e = GraphNode->value->Children.begin(); e != GraphNode->value->Children.end(); e++)
            {
                string E = e->first;
                transform(E.begin(), E.end(), E.begin(), ::toupper);
                if(E != "EDGE")
                    continue;
                GMLValueNode *EValue = dynamic_cast<GMLValueNode*>(e->second);
                if(EValue == NULL)
                    continue;

                GMLValueInt* source = GetValue<GMLValueInt>(EValue->value, "SOURCE");
                GMLValueInt* target = GetValue<GMLValueInt>(EValue->value, "TARGET");
                if(source == NULL || target == NULL)
                    continue;
                if(VertexRegister.find(source->value) == VertexRegister.end()
                || VertexRegister.find(target->value) == VertexRegister.end())
                    continue;

                bool Directed = GraphDirected;
                GMLValueNode* graphics = GetValue<GMLValueNode>(EValue->value, "GRAPHICS");
                if(graphics != NULL)
                {
                    GMLValueString* type = GetValue<GMLValueString>(graphics->value, "TYPE");
                    if(type != NULL)
                        Directed = type->value == "arc";
                }

                EdgeIterator ei;
                if(Directed)
                    ei = result.AddArc(VertexRegister[source->value], VertexRegister[target->value]);
                else
                    ei = result.AddEdge(VertexRegister[source->value], VertexRegister[target->value]);

                GMLValueString* label = GetValue<GMLValueString>(EValue->value, "LABEL");
                if(label != NULL)
                    (*ei)->SetLabel(label->value);
            }

            delete GMLTreeRoot;
            return result;
        }
コード例 #28
0
int main ()
{
    Graph G;

    string temp;
    cin >> temp;

    while (temp != "END")
    {
        if (!G.FindVertex(temp))
        {
            G.vertices.push_back(temp);
        }
        cin >> temp;
    }

    string key1, key2;
    int val;
    cin >> key1;

    while (key1 != "END")
    {
        cin >> key2; cin >> val;

        if (G.FindVertex(key1) && G.FindVertex(key2))
        {
            G.AddEdge(key1, key2, val);
        }

        cin >> key1;
    }

    int n;
    cin >> n;

    while (n != 0)
    {
        switch (n)
        {
            case 1:
            {
                string param;
                cin >> param;
                if (G.FindVertex(param)) cout << "1" << endl;
                else cout << "0" << endl;
                break;
            }
            case 2:
            {
                string param1, param2;
                cin >> param1; cin >> param2;
                cout << G.FindEdgeCost(param1, param2) << endl;
                break;
            }
            case 3:
            {
                string param1, param2;
                cin >> param1; cin >> param2;
                cout << G.IsReachable(param1, param2) << endl;
                break;
            }
        }

        cin >> n;
    }

    return 1;
}