【CodeChef - CLIQUED 】Bear and Clique Distances(建图,缩点技巧,思维)

题干:

【CodeChef - CLIQUED 】Bear and Clique Distances(建图,缩点技巧,思维)

解题报告:

  主要就是在于怎么处理那个前K个点:组成一个团。换句话说,缩成一个点。先直接当成每个点多了k条边来处理,T了。想想也是啊,要是K=1e5,那就是1e10条边了。。刚开始尝试了半天缩点,后来发现其实不用,只需要把这k个点都连到一个新点上,最后再连回去,然后直接Dijkstra就可以了 。只是相当于多了2*k条边而已。。真是好题,,,

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define F first
#define S second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair<int,int> PII;
const int MAX = 2e5 + 5;
const ll INF = 0x3f3f3f3f3f;
int n,m,tot;
int head[MAX];
bool vis[MAX];
int k;
ll X;
ll dis[MAX];
struct Edge {
	int to;
	ll w;
	int ne;
} e[MAX<<2];
struct Point {
	int pos;
	ll c;
	Point() {}
	Point(int pos,ll c):pos(pos),c(c) {}
	bool operator < (const Point b) const {
		return c > b.c;
	}
};
void add(int u,int v,ll w) {
	e[++tot].to = v;
	e[tot].w = w;
	e[tot].ne = head[u];
	head[u] = tot;
}
void Dijkstra(int st) {
	for(int i = 1; i<=n+1; i++) {
		dis[i] = INF;
		vis[i] = 0;
	}
//	for(int i = 1; i<=k; i++) dis[i] = X;
	dis[st] = 0;
	priority_queue<Point> pq;
	pq.push(Point(st,dis[st]));
	while(pq.size()) {
		Point cur = pq.top();
		pq.pop();
		if(vis[cur.pos]) continue;
		vis[cur.pos] = 1;
		for(int i = head[cur.pos]; i!=-1; i = e[i].ne) {
			if(dis[e[i].to] > dis[cur.pos] + e[i].w) {
				dis[e[i].to] = dis[cur.pos] + e[i].w;
				pq.push(Point(e[i].to,dis[e[i].to]));
			}

		}

	}
}
int main() 
{
	int t;
	cin>>t;
	while(t--) {
		int st;
		scanf("%d%d%lld%d%d",&n,&k,&X,&m,&st);
		//init
		tot=0;
		for(int i = 1; i<=n+1; i++) head[i] = -1;
		ll c;
		for(int i = 1; i<=k; i++) {
			add(i,n+1,0);
			add(n+1,i,X);
		}
		for(int a,b,i = 1; i<=m; i++) {
			scanf("%d%d%lld",&a,&b,&c);
			add(a,b,c);
			add(b,a,c);
		}
		Dijkstra(st);
		for(int i = 1; i<=n; i++) printf("%lld%c",dis[i],i == n ? '\n' : ' ');
	}
	return 0 ;
}

//		if(cur.pos<=k) {
//			for(int i = 1; i<=k; i++) {
//				if(vis[i]) continue;
//				if(dis[cur.pos] + X < dis[i]) {
//					dis[i] = dis[cur.pos] + X;
//					pq.push(Point(i,dis[i]));
//				}
//			}
//		}


////			if(e[i].to <= k) {
////				for(int i = head[n+1]; i!=-1; i = e[i].ne) {
////					if(dis[e[i].to] > dis[n+1] + e[i].w+X) {
////						dis[e[i].to] = dis[n+1] + e[i].w+X;
////						pq.push(Point(e[i].to,dis[e[i].to]));
////					}
////				}
////			}
//		}
//		if(cur.pos<=k) {
//			for(int i = head[n+1]; i!=-1; i = e[i].ne) {
//				if(e[i].to <= k) {
//					if(dis[e[i].to] > dis[cur.pos] + X) {
//						dis[e[i].to] = dis[cur.pos] + X;
//						pq.push(Point(e[i].to,dis[e[i].to]));
//					}
//				}
//				else if(dis[e[i].to] > dis[cur.pos] + e[i].w+X) {
//					dis[e[i].to] = dis[cur.pos] + e[i].w+X;
//					pq.push(Point(e[i].to,dis[e[i].to]));
//				}
//			}
//		}
//	}

 

上一篇:obj-c编程02:给类自动合成存取方法


下一篇:【???】字符串