예제 #1
0
파일: 1561.cpp 프로젝트: edisonhello/cpp
int dijdij(int st,int ed){
    v[0].reset(); v[1].reset();
    for(int i=0;i<111;++i)d[i].clear();
    d[st].pb(0);
    PQ<pii,vector<pii>,greater<pii>> pq; pq.push({0,st});
    while(pq.size()){
        while(pq.size() && v[1][pq.top().Y])pq.pop();
        if(pq.empty())break;
        pii now=pq.top(); pq.pop();
        int stp=v[0][now.Y]?1:0;
        PDE3(now,stp,pq);
        v[stp][now.Y]=1;
        for(pii e:G[now.Y]){
            d[e.X].pb(now.X+e.Y);
            sort(d[e.X].begin(),d[e.X].end());
            d[e.X].resize(unique(d[e.X].begin(),d[e.X].end())-d[e.X].begin());
            if(d[e.X].size()>2u){
                sort(d[e.X].begin(),d[e.X].end());
                d[e.X].pop_back();
            }
            if(now.X+e.Y<=d[e.X].back()){
                pq.push({now.X+e.Y,e.X});
            }
        }
    }
    if(d[ed].size()<2u)return -1;
    else return d[ed][1];
}
예제 #2
0
int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    vector<vector<pii>> edges(n);
    while(m--) {
        int u, v, w;
        scanf("%d %d %d", &u, &v, &w);
        edges[u].push_back({w, v});
        edges[v].push_back({w, u});
    }

    PQ pq;
    pq.push({0,0});
    while(!pq.empty()) {
        int dist = pq.top().first;
        int curr = pq.top().second;
        pq.pop();

        if (vis[curr] != false) continue;
        vis[curr] = true;

        /*
         * curr visited in "shortest path" order here
         */

        for(pii it : edges[curr]) {
            int ndist = it.first + dist;
            int next = it.second;
            pq.push({ndist, next});
        }
    }

    return 0;
}
예제 #3
0
파일: 1445.cpp 프로젝트: edisonhello/cpp
int main(){
    int n,m; cin>>n>>m;
    while(m--){
        int u,v; ll c; cin>>u>>v>>c;
        pq.push({c,pii(u,v)});
        E.eb(c,pii(u,v));
    }
    djs.init(1006);
    int pointsssss=1;
    ll firstttttt=0;
    while(pq.size()){
        if(!djs.C(pq.top().Y.X,pq.top().Y.Y)){
            G[pq.top().Y.X].eb(pq.top().Y.Y,pq.top().X);
            G[pq.top().Y.Y].eb(pq.top().Y.X,pq.top().X);
            ++pointsssss;
            firstttttt+=pq.top().X;
            djs.U(pq.top().Y.X,pq.top().Y.Y);
        } pq.pop();
    } if(pointsssss<n)return cout<<"-1 -1"<<endl,0;
    if(E.size()==n-1)return cout<<firstttttt<<" -1"<<endl,0;
    dfs(1,1,1);
    PDE1(firstttttt);
    ll diffffffff=1000000000000000000ll;
    for(auto i:E){
        if(p[0][i.Y.X]==i.Y.Y || p[0][i.Y.Y]==i.Y.X)continue;
        PDE1(i);
        diffffffff=min(diffffffff,i.X-lca(i.Y.X,i.Y.Y));
    } cout<<firstttttt<<" "<<firstttttt+diffffffff<<endl;
}
예제 #4
0
파일: qknn.hpp 프로젝트: Allefah/CMVS-PMVS
  /*! 
    Transforms the queue into a vector of indeces to points and returns it
    \param pl Vector which will hold the answer after function completes 
  */
  void answer(vector<long unsigned int>& pl)
  {
    pl.resize(K);
    for(int i=pl.size()-1;i >= 0;--i)
      {
	pl[i] = pq.top().second;
	pq.pop();
      }
  };
예제 #5
0
파일: qknn.hpp 프로젝트: Allefah/CMVS-PMVS
  /*! 
    Transforms the queue into a vector of indeces to points and a 
    vector of squared distances
    \param pl Vector which holds the point indeces after function completes
    \param pd Vector which holds the squared distances from query point
  */
  void answer(vector<long unsigned int>& pl, vector<double> &pd)
  {
    pl.resize(K);
    pd.resize(K);
    for(int i=pl.size()-1;i >= 0; --i)
      {
	pl[i] = pq.top().second;
	pd[i] = pq.top().first;
	pq.pop();
      }
  }
예제 #6
0
void test2() {
  PQ p;
  for (int i = 0;i < 10;i++) {
    p.push(10-i);
  }

  while (p.empty() == false) {
    cout << p.top() << endl;
    p.pop();
  }
}
예제 #7
0
// find top-k CC using boost graph representation
PQ find_top_CC(DeterministicGraph& PW, int k) {
	typename graph_traits <DeterministicGraph>::out_edge_iterator out1, out2;

	PQ pq; // priority queue for top-k CC
	int V = num_vertices(PW);
	bool *explored = new bool[V+1];
	for (int i = 0; i < V; ++i)
		explored[i] = false;
	int cc_number = 0;
	int unit_sized = 0;

	for (int i = 0; i < V; ++i) {
		if (!explored[i]) {
			// perform BFS for vertex i
			vector<int> CC;
			CC.push_back(i);
			explored[i] = true;
			vector<int>::size_type ix = 0;
			while (ix < CC.size()) {
				Vertex u = vertex(CC[ix], PW);
				for (tie(out1, out2) = out_edges(u, PW); out1 != out2; ++out1) {
					Vertex v = target(*out1, PW);
					if (!explored[v]) {
						CC.push_back(v);
						explored[v] = true;
					}
				}
				ix++;
			}
//			if (CC.size() > 5)
//				cout << cc_number << ": " << CC.size() << endl;
			if (CC.size() == 1) {
				unit_sized++;
			}
			cc_number++;

			// maintain CC priority queue
			int pq_size = pq.size();
			if (pq_size == k) {
				vector<int> top = pq.top();
				if (top.size() < CC.size()) {
					pq.pop();
					pq.push(CC);
				}
			}
			else
				pq.push(CC);
		}
	}
//	cout << "Total CCs: " << cc_number << endl;
//	cout << "Unit CCs: " << unit_sized << endl;
	return pq;
}
예제 #8
0
// find top-k CCs using vectors graph representation
PQ find_top_CC2(vector<vector<int> >& PW, int V, int k) {

	PQ pq; // priority queue for top-k CC
	map<int, bool> explored;
	for (int i = 0; i < V; ++i)
		explored[i] = false;
	int cc_number = 0;
	int unit_sized = 0;

	for (int i = 0; i < V; ++i) {
		if (!explored[i]) {
			// perform BFS for vertex i
			vector<int> CC;
			CC.push_back(i);
			explored[i] = true;
			vector<int>::size_type ix = 0;
			while (ix < CC.size()) {
				int pw_size = PW[CC[ix]].size();
				for (int j = 0; j < pw_size; ++j) {
					int v = PW[CC[ix]][j];
					if (!explored[v]) {
						CC.push_back(v);
						explored[v] = true;
					}
				}
				ix++;
			}
//			if (CC.size() > 5)
//				cout << cc_number << ": " << CC.size() << endl;
			if (CC.size() == 1) {
				unit_sized++;
			}
			cc_number++;

			// maintain CC priority queue
			int pq_size = pq.size();
			if (pq_size == k) {
				vector<int> top = pq.top();
				if (top.size() < CC.size()) {
					pq.pop();
					pq.push(CC);
				}
			}
			else
				pq.push(CC);
		}
	}
//	cout << "Total CCs: " << cc_number << endl;
//	cout << "Unit CCs: " << unit_sized << endl;
	return pq;
}
예제 #9
0
void test1() {
  PQ p;
  p.push(1);
  p.push(2);
  p.push(3);
  p.push(4);
  p.push(5);

  while (p.empty() == false) {
    cout << p.top() << endl;
    p.pop();
  }

}
예제 #10
0
int main()
{
    int numbers;
    int num;
    PQ myPQ;
    int sum;
    int totalCost;

    while (scanf("%d", &numbers) && numbers != 0)
    {
        totalCost = 0;

        for (int i = 0; i < numbers; i++)
        {
            scanf("%d", &num);
            myPQ.push(num);
        }

        while (true)
        {
            sum = myPQ.top();
            myPQ.pop();
            sum += myPQ.top();
            myPQ.pop();
            totalCost += sum;

            if (!myPQ.empty())
                myPQ.push(sum);
            else
                break;
        }

        printf("%d\n", totalCost);
    }

    return 0;
}
예제 #11
0
파일: 318.cpp 프로젝트: edisonhello/cpp
int main(){
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);
    int ks=0,n,m;while(rit(n,m),n){
        while(m--){
            int a,b,l;rit(a,b,l);
            G[a].pb({b,l}); G[b].pb({a,l});
        }
        pq.push({1,0});
        while(pq.size()){
            while(v[pq.top().X])pq.pop();
            v[pq.top().X]=1;
            
        }
    }
}
예제 #12
0
int dijkstra() {
  REP(i,n) REP(j,c+1) d[i][j] = INF, visited[i][j] = false;
  
  d[s][0] = 0;

  PQ pq;
  pq.push(State(s, 0, 0));

  while(!pq.empty()) {
    State u = pq.top(); pq.pop();

    if(u.node == e and u.fuel == 0) return u.cost;
    if(visited[u.node][u.fuel]) continue;

    visited[u.node][u.fuel] = true;
    /*
    // Create other states, when I just buy fuel
    int cost = u.cost; // current cost of fuel
    for(int f = u.fuel+1; f <= c; f++) { // try to fill until reach capacity c
      cost += prices[u.node];
      int& bcost = d[u.node][f];
      if(bcost > cost) {
        bcost = cost;
        pq.push(State(u.node, f, cost));
      }
    }*/

    FOREACH(el, g[u.node]) {
      if(el->second <= u.fuel) {
        int nfuel = u.fuel - el->second;
        if(u.cost < d[el->first][nfuel]) {
          d[el->first][nfuel] = u.cost;
          pq.push(State(el->first, nfuel, u.cost));
        }
      } else if(u.fuel < c) {
        int cost = u.cost + prices[u.node];
        int& bcost = d[u.node][u.fuel+1];
        if(bcost > cost) {
          bcost = cost;
          pq.push(State(u.node, u.fuel+1, cost));
        }
      }
    }
  }

  return INF;
}
예제 #13
0
파일: qknn.hpp 프로젝트: Allefah/CMVS-PMVS
  /*! 
    Updates the queue with the given distance and point
    \param dist Distance of point to be added
    \param p index of point to be added
    \return True if a point was added to the queue
  */
  bool update(double dist, long int p)
  {
    if(size() < K)
      {
	q_intelement tq(dist, p);
	pq.push(tq);
	return true;
      }
    else if(topdist() > dist)
      {
	pq.pop();
	q_intelement tq(dist, p);
	pq.push(tq);
	return true;
      }
    return false;
  }
예제 #14
0
파일: C.cpp 프로젝트: edisonhello/cpp
int main(){
    ll n,r,avg;
    cin>>n>>r>>avg;
    ll totgn=0,need=n*avg;
    for(int i=0;i<n;++i)cin>>a[i]>>b[i],totgn+=a[i],pq.push({b[i],r-a[i]});
    ll ans=0;
    while(totgn<need){
        // PDE2(pq.top().es,pq.top().lft);
        if(pq.top().lft>=need-totgn){
            ans+=pq.top().es*(need-totgn);
            break;
        }
        ans+=pq.top().es*pq.top().lft;
        totgn+=pq.top().lft;
        pq.pop();
    } cout<<ans<<endl;
}
예제 #15
0
void dfs(int rt, int fa)
{
     vis[rt] = true;
     if (adj[rt].size() == 1 && adj[rt][0] == fa) {f[rt].pb(v[rt]); return;}
     PQ q;
     q.push(v[rt]);
     for (int i=0; i<adj[rt].size(); i++)
     {
         int id = adj[rt][i];
         if (!vis[id] && id != fa) {dfs(id, rt);
         for (int j=0; j<f[id].size(); j++) q.push(f[id][j]);}
     }
     int cnt = 0;
     while (!q.empty() && cnt < 3)
     {
        f[rt].pb(q.top());
        q.pop();
        cnt++;           
     }
     sort(f[rt].begin(), f[rt].end(), greater<int>());
     return ;     
     }
예제 #16
0
파일: 1077.cpp 프로젝트: edisonhello/cpp
int main(){
    while(scanf("%d%d",&n,&m)!=EOF,n){
        init();
        for(int i=0,a,b,p,t;i<m;i++){
            a=rit(),b=rit(),p=rit(),t=rit();
            g[a][b]={t,p};
        }
        nb=rit(),ne=rit();
        rT(STst),rT(STed);
        ts=getT(STst);te=getT(STed);

        PQ<_pq,vector<_pq>,greater<_pq>> pq;
        pq.push({nb,ts});
        for(int _i=0;_i<n;++_i){
            while(S(pq)&&v[pq.top().pt]){
                pq.pop();
            }
            if(S(pq)==0)break;
            v[pq.top().pt]=1;
            d[pq.top().pt]=pq.top().tm;
            int np=pq.top().pt,nt=pq.top().tm;
            for(int i=1;i<=n;++i){                          // waiting time
                if(g[np][i].lo!=0 && d[i]>d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev)){
                    d[i]=d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev);
                    pq.push({i,d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev)});
                }
            }
        }
        cout<<ts<<" "<<te<<endl;
        if(d[ne]==0x7f7f7f7f){
            printf("No way\n");
            continue;
        }
        else{
            printf("--%d--\n",d[ne]);
        }
    }
}
예제 #17
0
파일: 1062.cpp 프로젝트: hzhua/ojprogram
int dijkstra(int start ,int goal ,int maxRank)
	{
	memset(dis , 0x7F ,sizeof(dis));
	memset(apr , 0 	  ,sizeof(apr));
	dis [start] = 0;
	que . size =0;
	que . push(start);
	while(!que . empty())
		{
		PQNode t;
		bool notGet = true;
		while(!que . empty())
			{
			t = que.top();
			que.pop();
			if(!apr[t . no]) 
				{
				notGet = false;
				break;
				}
			}
		if(notGet)break;
		for(Node *p = adj[t . no];p ; p=p->next)
			{
			if( rank [p->y] > maxRank) continue;
			if( rank [p->y] < maxRank - limRank) continue;
			if(dis[p->y] > dis[t .no] + p->w)
				{
				dis[p->y] = dis[t .no] + p->w;
				que .push(p->y);
				}
			}
		apr [t. no] = true;
		}
	if( !apr[goal] ) return -1;
	return dis [goal];
	}
예제 #18
0
int main(){
    CPPinput;
    int H,n; cin>>H>>n;
    // for(int i=1;i<=n;++i)cin>>t[i].first>>t[i].second;
    for(int i=1;i<=n;++i)cin>>t[i].first>>h[i],t[i].second=1e9;
    PQ<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> keytime;
    for(int i=1;i<=n;++i)keytime.emplace(t[i].first,i),keytime.emplace(t[i].second,i);
    if([&]()->bool{for(int i=1;i<=n;++i)if(h[i]==0)return 0;return 1;}())exit((cout<<-1<<endl,0));
    double nowh=H,nowt=0;
    int nowhole=0;
    multiset<int> activeh;
    while(nowh>eps){
        PDE(nowh,nowt);
        if(keytime.empty())exit((cout<<-1<<endl,0));
        if(nowhole==0){
            nowt=keytime.top().first;
            int i=keytime.top().second;
            keytime.pop();
            if(int(nowt)==t[i].second)continue;
            if(nowh<=h[i])continue;
            nowhole++;
            activeh.insert(h[i]);
            continue;
        }
        double nkt=keytime.top().first;
        int i=keytime.top().second;
        // keytime.pop();
        double dt=nkt-nowt;
        double dh=dt*nowhole;
        int nhh=*prev(activeh.end());
        if(nhh!=0){
            if(nowh-dh>=nhh){
                keytime.pop();
                nowt+=dt;
                nowh-=dh;
                if(int(nkt)==t[i].first){
                    if(nowh<=h[i]);
                    else{
                        nowhole++;
                        activeh.insert(h[i]);
                    }
                }
                else{
                    if(nowh<=h[i]);
                    else{
                        nowhole--;
                        activeh.erase(activeh.find(h[i]));
                    }
                }
            }
            else{
                dh=nowh-nhh;
                dt=dh/nowhole;
                nowt+=dt;
                nowh-=dh;
                activeh.erase(prev(activeh.end()));
                nowhole--;
            }
        }
        else{
            keytime.pop();
            if(dh>nowh)exit((cout<<fixed<<setprecision(14)<<nowt+nowh/nowhole<<endl,0));
            else{
                nowt+=dt;
                nowh-=dh;
                if(int(nkt)==t[i].first){
                    if(nowh<=h[i]);
                    else{
                        nowhole++;
                        activeh.insert(h[i]);
                    }
                }
                else{
                    if(nowh<=h[i]);
                    else{
                        nowhole--;
                        activeh.erase(activeh.find(h[i]));
                    }
                }
            }
        }
    }
    cout<<fixed<<setprecision(14)<<nowt<<endl;
}
예제 #19
0
파일: G.cpp 프로젝트: leonyan18/MyCode
int main()
{
    int n, m, l;
    while (scanf("%d%d%d", &n, &m, &l) == 3) {
        std::vector<std::vector<int>> graph(n);
        for (int i = 0, a, b; i < m; ++ i) {
            scanf("%d%d", &a, &b);
            a --, b --;
            graph[a].push_back(b);
            graph[b].push_back(a);
        }
        if (l == 1) {
            puts("1");
            continue;
        }
        l --;
        std::vector<std::vector<Info>> dp(1 << l, std::vector<Info>(n, Info { m + 1, 0 })),
            merged(n, std::vector<Info>(1 << l, Info { m + 1, 0 }));
        int root = l;
        for (int i = 0; i < l; ++ i) {
            dp[1 << i][i] = { 0, 1 };
        }
        for (int msk = 0; msk < 1 << l; ++ msk) {
            for (int u = 0; u < n; ++ u) {
                auto& ref = merged.at(u);
                for (int subset = msk; subset > 0; subset = subset - 1 & msk) {
                    if (lowbit(subset) == lowbit(msk)) {
                        update(ref.at(msk), add(dp.at(subset).at(u), ref.at(msk ^ subset)));
                    }
                }
            }
            for (int u = 0; u < n; ++ u) {
                for (int v : graph[u]) {
                    update(dp.at(msk).at(v), add(merged.at(u).at(msk), ONE));
                }
            }
            auto& ref = dp.at(msk);
            PQ<std::pair<int, int>> pq;
            for (int u = 0; u < n; ++ u) {
                pq.emplace(ref.at(u).first, u);
            }
            while (!pq.empty()) {
                auto top = pq.top();
                pq.pop();
                int u = top.second;
                if (top.first == ref.at(u).first) {
                    for (int v : graph.at(u)) {
                        Info todo = add(ref.at(u), ONE);
                        if (todo.first < ref.at(v).first) {
                            pq.emplace(todo.first, v);
                        }
                        update(ref.at(v), todo);
                    }
                }
            }
            for (int u = 0; u < n; ++ u) {
                update(merged.at(u).at(msk), dp.at(msk).at(u));
// fprintf(stderr, "%s %d %d %d\n", std::bitset<3>(msk).to_string().c_str(), u, dp.at(msk).at(u).first, dp.at(msk).at(u).second);
            }
        }
        printf("%d\n", merged.at(root).at((1 << l) - 1).second);
    }
}
예제 #20
0
int main(int argc, char* argv[]) {
	struct timeval ex_start, ex_finish;
	gettimeofday(&ex_start, NULL);

	// read parameters from command-line
	const string dataset = argv[1]; // filename of the dataset
	const long int V = atoi(argv[2]); // number of nodes
	const int R = atoi(argv[3]); // number of PWs
	const int k = atoi(argv[4]);         // number of seeds
	const string outfilename = argv[5]; // filename of the seeds

	cout << "Started processing..." <<endl;

	cout << "Graph: " << dataset << " k: " << k << endl;

	// read graph from the file
	WeightedGraph G(V);

	struct timeval t_start, t_finish;
	gettimeofday(&t_start, NULL);
	buildList(G, dataset);
	gettimeofday(&t_finish, NULL);
	cout << "* Read graph: " << print_time(t_start, t_finish) << "sec." << endl;

	// update scores
	struct timeval update_start, update_finish;
	gettimeofday(&update_start, NULL);

	std::map <int, double> scores;
	for (int i = 0; i < V; ++i) {
		scores[i] = 0;
	}
	int PWs = 0;
	double iter_time = 0;
	double pw_time = 0;
	double update_time = 0;
	double topcc_time = 0;

	// while there is still something in the directory to list
	for (int pw_num=0; pw_num<R; pw_num++) {

        // build PW
		struct timeval t_start, t_finish;
		gettimeofday(&t_start, NULL);

		vector<vector<int> > PW(V);
        bool built = buildPW(PW, dataset);

		gettimeofday(&t_finish, NULL);
		pw_time += print_time(t_start, t_finish);
//        cout << "* Read PW: " << print_time(t_start, t_finish) << "sec." << endl;

		if (built) {
            PWs++;
            cout << "PW: " << PWs << " Time: ";
            struct timeval iter_start, iter_finish;
            gettimeofday(&iter_start, NULL);

            // find scores
            struct timeval topcc_start, topcc_finish;
            gettimeofday(&topcc_start, NULL);
            PQ pq;
            pq = find_top_CC(PW, V, k);
            gettimeofday(&topcc_finish, NULL);
            topcc_time += print_time(topcc_start, topcc_finish);

            // update scores
            struct timeval assign_start, assign_finish;
            gettimeofday(&assign_start, NULL);

            for (int j = 0; j < k; ++j) {
                vector<int> top = pq.top();
                pq.pop();
                int top_size = top.size();
                for (int ix = 0; ix < top_size; ++ix) {
                    scores[top[ix]] += 1. / top_size;
//					cout << "node " << top[ix] << " score " << scores[top[ix]] << endl;
                }
//				cout << " size " << top.size() << endl;
            }
            gettimeofday(&assign_finish, NULL);
            update_time += print_time(assign_start, assign_finish);

            gettimeofday(&iter_finish, NULL);
            iter_time += print_time(iter_start, iter_finish);
            cout << print_time(t_start, iter_finish) << "sec." << endl;
        }
	}
	gettimeofday(&update_finish, NULL);
	cout << "* Accumulation phase: " << print_time(update_start, update_finish) << "sec." << endl;
//    cout << "  Average time per PW: " << iter_time/PWs << "sec." << endl;
	cout << "  ** Read PW: " << pw_time << "sec." << endl;
//    cout << "  ** Discover CC per PW: " << cc_time << "sec." << endl;
//    cout << "  ** Maintain PQ per PW: " << pq_time << "sec." << endl;
	cout << "  ** Find top-k CCs: " << topcc_time << "sec." << endl;
	cout << "  ** Assign scores: " << update_time << "sec." << endl;

	// select nodes
	struct timeval select_start, select_finish;
	gettimeofday(&select_start, NULL);

	std::set<int> S;
	std::map <int, bool> selected;
	for (int i = 0; i < V; ++i) {
		selected[i] = false;
	}

	typename graph_traits <WeightedGraph>::out_edge_iterator out1, out2;
	myWeight weight;

	for (int ix = 0; ix < k; ++ix) {
		// find max element
		int max_node;
		double max_score = 0;
		for (std::map<int, double>::iterator it = scores.begin(); it != scores.end(); ++it) {
//			cout << "inside for loop" << endl;
			if (it->second > max_score) {
				max_score = it->second;
				max_node = it->first;
			}
		}
//		cout << endl;
//		cout << "max_node: " << max_node << " max_score: " << max_score << endl;
		S.insert(max_node);
		selected[max_node] = true;
		scores.erase(max_node);

		// penalize scores of neighbors
		Vertex u = vertex(max_node, G);
		for (tie(out1, out2) = out_edges(u, G); out1 != out2; ++out1) {
			Vertex v = target(*out1, G);
			if (!selected[v]) {
				double p = get(weight, *out1);
				scores[v] *= (1 - p);
			}
//			cout << u << "-->" << v << endl;
		}
	}
	gettimeofday(&select_finish, NULL);
	cout << "* Penalization phase: " << print_time(select_start, select_finish) << "sec." << endl;

	for (std::set<int>::iterator it = S.begin(); it != S.end(); ++it) {
		std::cout << *it << ' ';
	}
	cout << endl;

	// write seeds to file
	struct timeval write_start, write_finish;
	gettimeofday(&write_start, NULL);

	std::ofstream myfile;
	myfile.open(outfilename.c_str());
//	myfile.open(seeds_filename.c_str());
//	cout << seeds_filename;
	myfile << k << " ";
	for (std::set<int>::iterator it = S.begin(); it != S.end(); ++it) {
		myfile << *it << ' ';
	}
	myfile.close();

	gettimeofday(&write_finish, NULL);
	cout << "* Wrote seeds to file: " << print_time(write_start, write_finish) << "sec." << endl;

	gettimeofday(&ex_finish, NULL);

	cout << endl;
	cout << "Total number of PWs: " << PWs << endl;

	cout << "* Execution time of Harvester: " << print_time(ex_start, ex_finish) << " sec." << endl;

	cout << "\nEnd of Harvester" << endl;
}
예제 #21
0
int main(int argc, char* argv[]) {
	struct timeval ex_start, ex_finish;
	gettimeofday(&ex_start, NULL);

	// read parameters from command-line
	const std::string dataset = argv[1]; // filename of the dataset
	const long int V = atoi(argv[2]); // number of nodes
	const std::string pw_dir = argv[3]; // folders containing PWs
	const int k = atoi(argv[4]);         // number of seeds
	const std::string outfilename = argv[5]; // filename of the seeds

	cout << "Started processing..." <<endl;

	cout << "Graph: " << dataset << " k: " << k << endl;

	// read graph from the file
	WeightedGraph G(V);

	struct timeval t_start, t_finish;
	gettimeofday(&t_start, NULL);
	buildList(G, dataset);
	gettimeofday(&t_finish, NULL);
	cout << "* Read graph: " << print_time(t_start, t_finish) << "sec." << endl;
//	return 1;

	// update scores
	struct timeval update_start, update_finish;
	gettimeofday(&update_start, NULL);

//	for sparsification graphs
//	std::ostringstream s;
//	s << "PW/G" << K << "/";
//	std::string pw_folder(s.str());
//	cout << pw_folder << endl;

	// For every filename in a PW directory create graph PW and update scores accordingly
	// solution found here: http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
	DIR *pdir = NULL;
//	pdir = opendir(pw_folder.c_str());
    pdir = opendir(pw_dir.c_str());
	struct dirent *pent = NULL;
	struct stat filestat;

	if (pdir == NULL) // if pdir wasn't initialised correctly
	{ // print an error message and exit the program
		cout << "\nERROR! pdir could not be initialised correctly";
		exit (3);
	} // end if

	std::map <int, double> scores;
	for (int i = 0; i < V; ++i) {
		scores[i] = 0;
	}
	int PWs = 0;
	double iter_time = 0;
	double pw_time = 0;
	double update_time = 0;
	double topcc_time = 0;

	// while there is still something in the directory to list
	while ( (pent = readdir(pdir)) != NULL ) {

		// if pent has not been initialised correctly
		if (pent == NULL) { // print an error message, and exit the program
			cout << "\nERROR! pent could not be initialised correctly";
			exit(3);
		}

		  string filepath = pw_dir + "/" + pent->d_name;
//		 string filepath = pw_folder + "/" + pent->d_name;

		 // check that files are text ones
		 // http://www.cplusplus.com/forum/beginner/10292/
		 if (stat(filepath.c_str(), &filestat)) continue;
		 if (S_ISDIR( filestat.st_mode ))         continue;


		struct timeval t_start, t_finish;
		gettimeofday(&t_start, NULL);
//        DeterministicGraph PW[V];
//        cout << "\n" << "New PW: ";
//        cout << pw_dir + pent->d_name << endl;
//        buildPW(*PW, pw_dir + pent->d_name);
//        vector<int>* PW = new vector<int>[V];
		vector<vector<int> > PW(V);
		 bool built = readPW2(PW, V, pw_dir + pent->d_name);
//		bool built = readPW2(PW, V, pw_folder + pent->d_name);

//        DeterministicGraph PW[V];
//        bool built = buildPW(*PW, V, pw_dir + pent->d_name);

//		vector<int> PW[V];
//		bool built = readPW(PW, V, "PW/MC/MC1_Sergei.txt");
//		DeterministicGraph PW[V];
//		bool built = buildPW(*PW, V, "PW/MC/MC1_Sergei.txt");


//        bool built = readPW(PW, V, "PW/MC/MC1_Sergei.txt");
//        cout << "nodes: " << num_vertices(*PW) << " edges: " << num_edges(*PW) << endl;
		gettimeofday(&t_finish, NULL);
		pw_time += print_time(t_start, t_finish);
//        cout << "* Read PW: " << print_time(t_start, t_finish) << "sec." << endl;

		if (built) {
			PWs++;
//        	cout << PWs << ": " << pent->d_name << " ";
			struct timeval iter_start, iter_finish;
			gettimeofday(&iter_start, NULL);

			// find scores
			struct timeval topcc_start, topcc_finish;
			gettimeofday(&topcc_start, NULL);
			PQ pq;
//			pq = find_top_CC(*PW, k);
			pq = find_top_CC2(PW, V, k);
			gettimeofday(&topcc_finish, NULL);
			topcc_time += print_time(topcc_start, topcc_finish);

			// update scores
			struct timeval assign_start, assign_finish;
			gettimeofday(&assign_start, NULL);

			for (int j=0; j<k; ++j) {
				vector<int> top = pq.top();
				pq.pop();
				int top_size = top.size();
				for (int ix = 0; ix < top_size; ++ix) {
					scores[top[ix]] += 1./top_size;
//					cout << "node " << top[ix] << " score " << scores[top[ix]] << endl;
				}
//				cout << " size " << top.size() << endl;
			}

//			for (int j=0; j<k; ++j) {
//				CC top = pq.top();
//				pq.pop();
//				int top_size = top.nodes.size();
//				for (int ix = 0; ix < top_size; ++ix) {
//					scores[top.nodes[ix]] += 1./top_size;
////					cout << "node " << top.nodes[ix] << " score " << scores[top.nodes[ix]] << endl;
//				}
////				cout << "cc " << top.idx << " size " << top.nodes.size() << endl;
//			}
			gettimeofday(&assign_finish, NULL);
			update_time += print_time(assign_start, assign_finish);

//			break;
			gettimeofday(&iter_finish, NULL);
			iter_time += print_time(iter_start, iter_finish);
//			cout << print_time(iter_start, iter_finish) << endl;
//			if (PWs == 3)
//				break;
		}
	}
	gettimeofday(&update_finish, NULL);
	cout << "* Accumulation phase: " << print_time(update_start, update_finish) << "sec." << endl;
//    cout << "  Average time per PW: " << iter_time/PWs << "sec." << endl;
	cout << "  ** Read PW: " << pw_time << "sec." << endl;
//    cout << "  ** Discover CC per PW: " << cc_time << "sec." << endl;
//    cout << "  ** Maintain PQ per PW: " << pq_time << "sec." << endl;
	cout << "  ** Find top-k CCs: " << topcc_time << "sec." << endl;
	cout << "  ** Assign scores: " << update_time << "sec." << endl;

	// select nodes
	struct timeval select_start, select_finish;
	gettimeofday(&select_start, NULL);

	std::set<int> S;
	std::map <int, bool> selected;
	for (int i = 0; i < V; ++i) {
		selected[i] = false;
	}

	typename graph_traits <WeightedGraph>::out_edge_iterator out1, out2;
	myWeight weight;

	for (int ix = 0; ix < k; ++ix) {
		// find max element
		int max_node;
		double max_score = 0;
		for (std::map<int, double>::iterator it = scores.begin(); it != scores.end(); ++it) {
//			cout << "inside for loop" << endl;
			if (it->second > max_score) {
				max_score = it->second;
				max_node = it->first;
			}
		}
//		cout << endl;
//		cout << "max_node: " << max_node << " max_score: " << max_score << endl;
		S.insert(max_node);
		selected[max_node] = true;
		scores.erase(max_node);

		// penalize scores of neighbors
		Vertex u = vertex(max_node, G);
		for (tie(out1, out2) = out_edges(u, G); out1 != out2; ++out1) {
			Vertex v = target(*out1, G);
			if (!selected[v]) {
				double p = get(weight, *out1);
				scores[v] *= (1 - p);
			}
//			cout << u << "-->" << v << endl;
		}
	}
	gettimeofday(&select_finish, NULL);
	cout << "* Penalization phase: " << print_time(select_start, select_finish) << "sec." << endl;

	for (std::set<int>::iterator it = S.begin(); it != S.end(); ++it) {
		std::cout << *it << ' ';
	}
	cout << endl;

	// write seeds to file
	struct timeval write_start, write_finish;
	gettimeofday(&write_start, NULL);

//	for sparsified graphs
//	std::ostringstream seeds_name;
//	seeds_name << "seeds/seeds" << K << ".txt";
//	std::string seeds_filename(seeds_name.str());

	std::ofstream myfile;
	myfile.open(outfilename.c_str());
//	myfile.open(seeds_filename.c_str());
//	cout << seeds_filename;
	myfile << k << " ";
	for (std::set<int>::iterator it = S.begin(); it != S.end(); ++it) {
		myfile << *it << ' ';
	}
	myfile.close();

	gettimeofday(&write_finish, NULL);
	cout << "* Wrote seeds to file: " << print_time(write_start, write_finish) << "sec." << endl;

	closedir(pdir);
	gettimeofday(&ex_finish, NULL);

	cout << endl;
	cout << "Total number of PWs: " << PWs << endl;

	cout << "* Execution time of Harvester: " << print_time(ex_start, ex_finish) << " sec." << endl;

	cout << "\nEnd of Harvester" << endl;
}