SRM 627 D1L2:GraphInversions,DFS,求所有指定长度的路径, Binary indexed tree (BIT)

题目:http://community.topcoder.com/stat?c=problem_statement&pm=13275&rd=16008

由于图中边数不多,选择DFS遍历所有路径,计算路径Inversions时使用了一个R[] 数组,可以在O(N)时间内得到路径Inversions,又因为该图所以路径条数为O(N^2),算法复杂度为O(N^3),对于N为1000的限制来说,复杂度较高,但实际测试中,最慢的测试用例费时700多ms,没有超时。若要减小复杂度,需要更高效的算法来计算路径的Inversions,使用 Binary indexed tree (BIT)数据结构可以达到O(logN), 总复杂的减小到O(N^2logN)。

代码:

#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;

#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair

/*************** Program Begin **********************/
const int INF = 1000000000;
class GraphInversions {
public:
	vector <int> V, A, B, adj[1001];
	bool visited[1005];	// 顶点的访问状态
	int R[1005];		// 用于计算 Inversions, R[weight] 表示当前路径上权值为weight的顶点的个数
	int N, K, ans;
	void DFS(int u, int d, int invs)
	{
		if (d == K) {
			ans = min(ans, invs);
		} else if (d < K) {
			for (int i = 0; i < adj[u].size(); i++) {
				int w = adj[u][i];
				if (visited[w]) {
					continue;
				}
				visited[w] = true;
				++R[ V[w] ];
				DFS(w, d + 1, invs + accumulate(R + V[w] + 1, R + 1001, 0));
				--R[ V[w] ];		// 将顶点从该路径排除
				visited[w] = false;	// 另一条路径依然可以使用该顶点
			}
		}

	}
	int getMinimumInversions(vector <int> A, vector <int> B, vector <int> V, int K) {
		int res = INF;
		this->N = A.size();
		this->V = V;
		this->K = K;

		for (int i = 0; i < N; i++) {
			adj[ A[i] ].push_back(B[i]);
			adj[ B[i] ].push_back(A[i]);
		}

		for (int i = 0; i < N; i++) {	// 依次遍历所有顶点,以每个顶点为起始点进行DFS
			ans = INF;
			memset(visited, 0, sizeof(visited));
			memset(R, 0, sizeof(R));
			visited[i] = true;	// 这一步不要忘,起始点访问状态应为TRUE
			++R[ V[i] ];		// 将起始点加入到路径中
			DFS(i, 1, 0);
			res = min(res, ans);
		}
		return (res == INF ? -1 : res);
	}
};

/************** Program End ************************/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值