![](http://acm.fzu.edu.cn/image/problem.gif)
Accept: 20 Submit: 28
Time Limit: 1000 mSec Memory Limit : 131072 KB
Problem Description
A国和B国正在进行一场战争,A国有n座城市,这些城市被m条有向道路相连,这些道路不会形成环路。其中有一部分城市比较特殊,其拥有粮仓,拥有粮仓的城市不能被其他城市到达,粮食可以从粮仓经过一些道路送往任意一座城市,现在B国的国王想要破坏一座A国的城市,粮食不能经过被破坏的城市。问破坏哪一座城市,可以使得最多的城市断粮。
Input
第一行两个数n和m(n<=1000,m<=10000)
接下来m行,每行两个数字a和b,表示城市a有一条连向城市b的道路
Output
输出一个数,表示被破坏的城市的序号,如果有多个城市满足条件,输出序号最小的那个城市
Sample Input
3 31 22 31 3
Sample Output
1
Source
FOJ有奖月赛-2015年11月
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<iostream>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1,class T2>inline void gmax(T1 &a,T2 b){if(b>a)a=b;}
template <class T1,class T2>inline void gmin(T1 &a,T2 b){if(b<a)a=b;}
const int N=1010,M=0,Z=1e9+7,ms63=1061109567;
int n,m,x,y;
int tim,num;
vector<int>a[N],st;
int ind[N],e[N];
void dfs(int x)
{
if(e[x]==tim)return;
e[x]=tim;
--num;
for(int i=a[x].size()-1;~i;--i)dfs(a[x][i]);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int ansnum=0,ansp;
for(int i=1;i<=n;i++)a[i].clear(),ind[i]=0;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
a[x].push_back(y);
++ind[y];
}
st.clear();
for(int i=1;i<=n;i++)if(ind[i]==0)st.push_back(i);
for(int i=1;i<=n;i++)
{
e[i]=++tim;
num=n;
for(int j=st.size()-1;~j;--j)dfs(st[j]);
if(num>ansnum)
{
ansnum=num;
ansp=i;
}
}
printf("%d\n",ansp);
}
return 0;
}
/*
【trick&&吐槽】
这道题破坏的不一定是粮仓。
只是因为数据水,所以很容易AC,然而维护逻辑的正确性还是至关重要啊。
【题意】
给你一个n(1000)个点,m(10000)条有向边的 有向无环图。
入度为0的点表示为粮仓,粮仓可以沿着有向边向后输送粮食。
我们要破坏这个图上的某一点。
问你要破坏哪个点,可以使得断粮的城市尽可能多
【类型】
图论
【分析】
向优秀在做法一直想不到,于是干脆暴力,然而就过了。
因为这题点数并不多,枚举点,然后来一遍拓扑排序或dfs,走不到的点计数,更新答案即可AC
有一个我犯蠢的地方就是,还是dfs好写>_<然而我却写了拓扑
【时间复杂度&&优化】
O(n(n+m))
【数据】
5 4
1 3
2 3
3 4
3 5
10 8
1 3
2 3
3 4
3 5
6 7
7 8
8 9
9 10
*/