C - Gr-idian MST
Time limit : 2sec / Memory limit : 256MB
Score : 500 points
Problem Statement
On an xy plane, in an area satisfying 0≤x≤W,0≤y≤H, there is one house at each and every point where both x and y are integers.
There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the ycoordinates are equal and the difference between the x coordinates is 1.
The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is pi for any value of j, while the cost of paving a road between houses on coordinates(i,j) and (i,j+1) is qj for any value of i.
Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.
Constraints
- 1≦W,H≦105
- 1≦pi≦108(0≦i≦W−1)
- 1≦qj≦108(0≦j≦H−1)
- pi(0≦i≦W−1) is an integer.
- qj(0≦j≦H−1) is an integer.
Input
Inputs are provided from Standard Input in the following form.
W H p0 : pW−1 q0 : qH−1
Output
Output an integer representing the minimum total cost.
Sample Input 1
2 2 3 5 2 7
Sample Output 1
29
It is enough to pave the following eight roads.
- Road connecting houses at (0,0) and (0,1)
- Road connecting houses at (0,1) and (1,1)
- Road connecting houses at (0,2) and (1,2)
- Road connecting houses at (1,0) and (1,1)
- Road connecting houses at (1,0) and (2,0)
- Road connecting houses at (1,1) and (1,2)
- Road connecting houses at (1,2) and (2,2)
- Road connecting houses at (2,0) and (2,1)
Sample Input 2
4 3 2 4 8 1 2 9 3
Sample Output 2
60
类似于克鲁斯卡尔算法求最小生成树。只不过题目中给的点到点的值和往常不同。
/* *********************************************** Author :guanjun Created Time :2016/10/11 14:54:59 File Name :1.cpp ************************************************ */ #include <bits/stdc++.h> #define ull unsigned long long #define ll long long #define mod 90001 #define INF 0x3f3f3f3f #define maxn 10010 #define cle(a) memset(a,0,sizeof(a)) const ull inf = 1LL << 61; const double eps=1e-5; using namespace std; priority_queue<int,vector<int>,greater<int> >pq; struct Node{ int x,y; }; struct cmp{ bool operator()(Node a,Node b){ if(a.x==b.x) return a.y> b.y; return a.x>b.x; } }; bool cmp(int a,int b){ return a>b; } typedef pair<ll,int> pii; vector<pii>v; int main() { #ifndef ONLINE_JUDGE //freopen("in.txt","r",stdin); #endif //freopen("out.txt","w",stdout); ll h,w,x; while(scanf("%lld %lld",&w,&h)!=EOF){ v.clear(); for(int i=0;i<w;i++){ scanf("%lld",&x); v.push_back({x,0}); } for(int i=0;i<h;i++){ scanf("%lld",&x); v.push_back({x,1}); } sort(v.begin(),v.end()); ll ans=0; w++; h++; for(int i=0;i<v.size();i++){ if(v[i].second==1){ ans+=w*v[i].first; h--; } else { ans+=h*v[i].first; w--; } } printf("%lld\n",ans); } return 0; }
欢迎关注公众号:
![](https://images.cnblogs.com/cnblogs_com/pk28/1069498/o_qrcode_for_gh_db07a03aaa56_344.jpg)