HDU 6166 Senior Pan 二进制分组 + 迪杰斯特拉算法
Senior Pan
Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Problem Description
Senior Pan fails in his discrete math exam again. So he asks Master ZKC to give him graph theory problems everyday.
The task is simple : ZKC will give Pan a directed graph every time, and selects some nodes from that graph, you can calculate the minimum distance of every pair of nodes chosen in these nodes and now ZKC only cares about the minimum among them. That is still too hard for poor Pan, so he asks you for help.
Input
The first line contains one integer T, represents the number of Test Cases.1≤T≤5.Then T Test Cases, for each Test Cases, the first line contains two integers n,m representing the number of nodes and the number of edges.1≤n,m≤100000
Then m lines follow. Each line contains three integers xi,yi representing an edge, and vi representing its length.1≤xi,yi≤n,1≤vi≤100000
Then one line contains one integer K, the number of nodes that Master Dong selects out.1≤K≤n
The following line contains K unique integers ai, the nodes that Master Dong selects out.1≤ai≤n,ai!=aj
Output
For every Test Case, output one integer: the answer
Sample Input
1
5 6
1 2 1
2 3 3
3 1 3
2 5 1
2 4 2
4 3 1
3
1 3 5
Sample Output
Case #1: 2
Source
题解:
答案路径的起点终点,必然是不同的点,也就是在二进制下存在一位是不同,根据每一位分组,0,1分别分为起点集和终点集
跑一遍多源多汇最短路即可,就是40次dij
#include <bits/stdc++.h> inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;} using namespace std; const int N = 200000; vector<pair<int,int > > G[N]; int vis[N], n, m, go[N], k, dis[N]; void init() { memset(vis,0,sizeof(vis)); for(int i = 0; i <= n; ++i) G[i].clear(); } priority_queue<pair<int,int> , vector<pair<int,int> > , greater<pair<int,int> > > q; void dij() { for(int i = 0; i <= n; ++i) dis[i] = 1000000000; for(int i = 0; i <= n; ++i) if(go[i] == 1) { dis[i] = 0; q.push(make_pair(0,i)); } while(!q.empty()) { pair<int,int >now = q.top(); q.pop(); int v = now.second; for(auto son : G[v]) { int to = son.first; if(dis[to] > dis[v] + son.second){ dis[to] = dis[v] + son.second; q.push(make_pair(dis[to],to)); } } } } int main() { int T, cas = 1, x, u, v, w; cin >> T; while(T--) { cin >> n >> m; init(); for(int i = 1; i <= m; ++i) { scanf("%d%d%d",&u,&v,&w); G[u].push_back(make_pair(v,w)); } cin >> k; for(int i = 1; i <= k; ++i) scanf("%d",&x), vis[x] = 1; int ans = 2000000000; for(int j = 0; j < 20; ++j) { for(int i = 1; i <= n; ++i) { go[i] = 0; if(!vis[i]) continue; if((i>>j)&1) go[i] = 1; else go[i] = -1; } dij(); for(int i = 1; i <= n; ++i) { if(!vis[i]) continue; if(go[i] == -1) ans = min(ans,dis[i]); } for(int i = 1; i <= n; ++i) { go[i] = 0; if(!vis[i]) continue; if((i>>j)&1) go[i] = -1; else go[i] = 1; } dij(); for(int i = 1; i <= n; ++i) { if(!vis[i]) continue; if(go[i] == -1) ans = min(ans,dis[i]); } } cout << "Case #" << (cas++) << ":" << " " << ans << endl; } }