1001. Battle Over Cities - Hard Version (35)
It is vitally important to have all the cities connected by highways in a war. If a city is conquered by the enemy, all the highways from/toward that city will be closed. To keep the rest of the cities connected, we must repair some highways with the minimum cost. On the other hand, if losing a city will cost us too much to rebuild the connection, we must pay more attention to that city.
Given the map of cities which have all the destroyed and remaining highways marked, you are supposed to point out the city to which we must pay the most attention.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 2 numbers N (<=500), and M, which are the total number of cities, and the number of highways, respectively. Then M lines follow, each describes a highway by 4 integers:
City1 City2 Cost Status
where City1 and City2 are the numbers of the cities the highway connects (the cities are numbered from 1 to N), Cost is the effort taken to repair that highway if necessary, and Status is either 0, meaning that highway is destroyed, or 1, meaning that highway is in use.
Note: It is guaranteed that the whole country was connected before the war.
Output Specification:
For each test case, just print in a line the city we must protest the most, that is, it will take us the maximum effort to rebuild the connection if that city is conquered by the enemy.
In case there is more than one city to be printed, output them in increasing order of the city numbers, separated by one space, but no extra space at the end of the line. In case there is no need to repair any highway at all, simply output 0.
Sample Input 1:4 5 1 2 1 1 1 3 1 1 2 3 1 0 2 4 1 1 3 4 1 0Sample Output 1:
1 2Sample Input 2:
4 5 1 2 1 1 1 3 1 1 2 3 1 0 2 4 1 1 3 4 2 1Sample Output 2:
0
用并查集做的最小生成树
但是好奇怪的是题目写着N《=500 刚开始我MAXN开510,V的大小开1e5,最后两个测试点段错误。迷
#include<iostream>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e5;
int fa[maxn],cost[maxn];
struct node{
int from,to;
int w,s;
void read(){cin>>from>>to>>w>>s;}
bool operator < (const node &a) const{
if(s==a.s)return w<a.w;
return s>a.s;
}
}v[maxn];
int find(int x){
int a=x;
while(x!=fa[x])x=fa[x];
while(a!=fa[x]){
int tmp=a;
a=fa[a];
fa[tmp]=x;
}
return x;
}
int main(){
ios::sync_with_stdio(false);
int n,m,res=0;
cin>>n>>m;
for(int i=0;i<m;++i)v[i].read();
sort(v,v+m);
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j)fa[j]=j;
int cnt=n-2;
cost[i]=0;
for(int j=0;j<m;++j){
if(v[j].from==i||v[j].to==i)continue;
int fx=find(v[j].from),fy=find(v[j].to);
if(fx==fy)continue;
--cnt;
if(!v[j].s)cost[i]+=v[j].w;
fa[fx]=fy;
}
if(cnt>0)cost[i]=inf;
res=max(cost[i],res);
}
if(!res){
cout<<0;
return 0;
}
bool flag=false;
for(int i=1;i<=n;++i)
if(res==cost[i]){
if(flag)cout<<" ";
flag=true;
cout<<i;
}
return 0;
}